1# Using ImagePacker to Encode Pictures
2
3Image encoding refers to the process of encoding a picture into an archived image in different formats (only in JPEG and HEIF currently) for subsequent processing, such as storage and transmission.
4
5## How to Develop
6
7Read [Image API Reference](../../reference/apis-image-kit/js-apis-image.md#imagepacker) for APIs related to image encoding.
8
9### Encoding Images into File Streams
10
111. Create an **ImagePacker** object.
12
13   ```ts
14   // Import the required module.
15   import { image } from '@kit.ImageKit';
16
17   const imagePackerApi = image.createImagePacker();
18   ```
19
202. Set the encoding output stream and encoding parameters.
21
22   **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.
23
24      > **NOTE**
25      >
26      > According to the MIME protocol, the standard encoding format is image/jpeg. When the APIs provided by the image module are used for encoding, **PackingOption.format** must be set to **image/jpeg**. The file name extension of the encoded image file can be .jpg or .jpeg, and the file can be used on platforms that support image/jpeg decoding.
27
28      ```ts
29      let packOpts: image.PackingOption = {
30        format: "image/jpeg",
31        quality: 98,
32        bufferSize: 10,
33        desiredDynamicRange: image.PackingDynamicRange.AUTO,
34        needsPackProperties: true
35      };
36      ```
37
383. Encode the image and save the encoded image.
39
40   ```ts
41   import { BusinessError } from '@kit.BasicServicesKit';
42   imagePackerApi.packing(picture, packOpts).then( (data : ArrayBuffer) => {
43     console.info('Succeeded in packing the image.'+ data);
44   }).catch((error : BusinessError) => {
45     console.error('Failed to pack the image. And the error is: ' + error);
46   })
47   ```
48
49### Encoding Images into Files
50
51During encoding, you can pass in a file path so that the encoded memory data is directly written to the file.
52
53   ```ts
54  const context : Context = getContext(this);
55  const path : string = context.cacheDir + "/picture.jpg";
56  let file = fileIo.openSync(path, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
57  imagePackerApi.packToFile(picture, file.fd, packOpts).then(() => {
58    console.info('Succeeded in packing the image to file.');
59  }).catch((error : BusinessError) => {
60    console.error('Failed to pack the image. And the error is: ' + error);
61  })
62   ```
63