• 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, WebP, and PNG currently) for subsequent processing, such as storage and transmission.
4
5## How to Develop
6
7Read [Image API Reference](../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 : image.PackingOption = { 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   import {BusinessError} from '@ohos.base'
34   imagePackerApi.packing(pixelMap, packOpts).then( (data : ArrayBuffer) => {
35     // data is the file stream obtained after packing. You can write the file and save it to obtain an image.
36   }).catch((error : BusinessError) => {
37     console.error('Failed to pack the image. And the error is: ' + error);
38   })
39   ```
40
41   Method 2: Use the **ImageSource** object for encoding.
42
43   ```ts
44   import {BusinessError} from '@ohos.base'
45   imagePackerApi.packing(imageSource, packOpts).then( (data : ArrayBuffer) => {
46       // data is the file stream obtained after packing. You can write the file and save it to obtain an image.
47   }).catch((error : BusinessError) => {
48     console.error('Failed to pack the image. And the error is: ' + error);
49   })
50   ```
51