1# 使用ImagePacker完成多图对象编码 2 3图片编码指将Picture多图对象编码成不同格式的存档图片(当前仅支持打包为JPEG 和 HEIF 格式),用于后续处理,如保存、传输等。 4 5## 开发步骤 6 7图片编码相关API的详细介绍请参见:[图片编码接口说明](../../reference/apis-image-kit/js-apis-image.md#imagepacker)。 8 9### 图片编码进文件流 10 111. 创建图像编码ImagePacker对象。 12 13 ```ts 14 // 导入相关模块包 15 import { image } from '@kit.ImageKit'; 16 17 const imagePackerApi = image.createImagePacker(); 18 ``` 19 202. 设置编码输出流和编码参数。 21 22 format为图像的编码格式;quality为图像质量,范围从0-100,100为最佳质量 23 24 > **说明:** 25 > 根据MIME标准,标准编码格式为image/jpeg。当使用image编码时,PackingOption.format设置为image/jpeg,image编码后的文件扩展名可设为.jpg或.jpeg,可在支持image/jpeg解码的平台上使用。 26 27 ```ts 28 let packOpts: image.PackingOption = { 29 format: "image/jpeg", 30 quality: 98, 31 bufferSize: 10, 32 desiredDynamicRange: image.PackingDynamicRange.AUTO, 33 needsPackProperties: true 34 }; 35 ``` 36 373. 进行图片编码,并保存编码后的图片。 38 39 ```ts 40 import { BusinessError } from '@kit.BasicServicesKit'; 41 imagePackerApi.packing(picture, packOpts).then( (data : ArrayBuffer) => { 42 console.info('Succeeded in packing the image.'+ data); 43 }).catch((error : BusinessError) => { 44 console.error('Failed to pack the image. And the error is: ' + error); 45 }) 46 ``` 47 48### 图片编码进文件 49 50在编码时,开发者可以传入对应的文件路径,编码后的内存数据将直接写入文件。 51 52 ```ts 53 const context : Context = getContext(this); 54 const path : string = context.cacheDir + "/picture.jpg"; 55 let file = fileIo.openSync(path, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE); 56 imagePackerApi.packToFile(picture, file.fd, packOpts).then(() => { 57 console.info('Succeeded in packing the image to file.'); 58 }).catch((error : BusinessError) => { 59 console.error('Failed to pack the image. And the error is: ' + error); 60 }) 61 ``` 62