• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Image Encoding
2
3Image encoding refers to the process of encoding a pixel map into an archived image in different formats (only in JPEG and WebP currently) for subsequent processing, such as storage and transmission.
4
5## How to Develop
6
7Read [Image](../reference/apis/js-apis-image.md#imagepacker) for APIs related to image encoding.
8
91. Create an **ImagePacker** object.
10
11   ```ts
12   // Import the required module.
13   import image from '@ohos.multimedia.image';
14
15   const imagePackerApi = image.createImagePacker();
16   ```
17
182. Set the encoding output stream and encoding parameters.
19
20   **format** indicates the image encoding format, and **quality** indicates the image quality. The value ranges from 0 to 100, and the value 100 indicates the optimal quality.
21
22   ```ts
23   let packOpts = { format:"image/jpeg", quality:98 };
24   ```
25
263. [Create a PixelMap object or an ImageSource object](image-decoding.md).
27
284. Encode the image and save the encoded image.
29
30   Method 1: Use the **PixelMap** object for encoding.
31
32   ```ts
33   imagePackerApi.packing(pixelMap, packOpts).then( data => {
34     // data is the file stream obtained after packing. You can write the file and save it to obtain an image.
35   }).catch(error => {
36     console.error('Failed to pack the image. And the error is: ' + error);
37   })
38   ```
39
40   Method 2: Use the **ImageSource** object for encoding.
41
42   ```ts
43   imagePackerApi.packing(imageSource, packOpts).then( data => {
44       // data is the file stream obtained after packing. You can write the file and save it to obtain an image.
45   }).catch(error => {
46     console.error('Failed to pack the image. And the error is: ' + error);
47   })
48   ```
49