1# 使用ImagePacker完成多图对象编码 2<!--Kit: Image Kit--> 3<!--Subsystem: Multimedia--> 4<!--Owner: @aulight02--> 5<!--Designer: @liyang_bryan--> 6<!--Tester: @xchaosioda--> 7<!--Adviser: @zengyawen--> 8 9图片编码指将Picture多图对象编码成不同格式的图片文件(当前仅支持编码为JPEG 和 HEIF 格式),用于后续处理,如保存、传输等。 10 11## 开发步骤 12 13图片编码相关API的详细介绍请参见:[图片编码接口说明](../../reference/apis-image-kit/arkts-apis-image-ImagePacker.md)。 14 15### 图片编码进文件流 16 171. 创建图像编码ImagePacker对象。 18 19 ```ts 20 // 导入相关模块包。 21 import { image } from '@kit.ImageKit'; 22 23 const imagePackerApi = image.createImagePacker(); 24 ``` 25 262. 设置编码输出流和编码参数。 27 28 format为图像的编码格式;quality为图像质量,范围从0-100,100为最佳质量 29 30 > **说明:** 31 > 根据MIME标准,标准编码格式为image/jpeg。当使用image编码时,PackingOption.format设置为image/jpeg,image编码后的文件扩展名可设为.jpg或.jpeg,可在支持image/jpeg解码的平台上使用。 32 33 ```ts 34 let packOpts: image.PackingOption = { 35 format: "image/jpeg", 36 quality: 98, 37 bufferSize: 10, 38 desiredDynamicRange: image.PackingDynamicRange.AUTO, 39 needsPackProperties: true 40 }; 41 ``` 42 433. 进行图片编码,并保存编码后的图片。在进行编码前,需要先通过解码获取picture,可参考[使用ImageSource完成多图对象解码](./image-picture-decoding.md)。 44 45 ```ts 46 import { BusinessError } from '@kit.BasicServicesKit'; 47 48 function packing(picture: image.Picture, packOpts: image.PackingOption) { 49 const imagePackerApi = image.createImagePacker(); 50 imagePackerApi.packing(picture, packOpts).then( (data : ArrayBuffer) => { 51 console.info('Succeeded in packing the image.'+ data); 52 }).catch((error : BusinessError) => { 53 console.error(`Failed to pack the image, error.code: ${error.code}, error.message: ${error.message}`); 54 }) 55 } 56 ``` 57 58### 图片编码进文件 59 60在编码时,开发者可以传入对应的文件路径,编码后的内存数据将直接写入文件。在进行编码前,需要先通过解码获取picture,可参考[使用ImageSource完成多图对象解码](./image-picture-decoding.md)。 61 62 ```ts 63import { BusinessError } from '@kit.BasicServicesKit'; 64import { fileIo } from '@kit.CoreFileKit'; 65import { image } from '@kit.ImageKit'; 66 67function packToFile(picture: image.Picture, packOpts: image.PackingOption, context: Context) { 68 const path : string = context.cacheDir + "/picture.jpg"; 69 let file = fileIo.openSync(path, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE); 70 const imagePackerApi = image.createImagePacker(); 71 imagePackerApi.packToFile(picture, file.fd, packOpts).then(() => { 72 console.info('Succeeded in packing the image to file.'); 73 }).catch((error : BusinessError) => { 74 console.error('Failed to pack the image. And the error is: ' + error); 75 }) 76} 77 ``` 78