1# 图片编码 2 3图片编码指将PixelMap编码成不同格式的存档图片(当前仅支持打包为JPEG、WebP 和 png 格式),用于后续处理,如保存、传输等。 4 5## 开发步骤 6 7图片编码相关API的详细介绍请参见:[图片编码接口说明](../reference/apis/js-apis-image.md#imagepacker)。 8 91. 创建图像编码ImagePacker对象。 10 11 ```ts 12 // 导入相关模块包 13 import image from '@ohos.multimedia.image'; 14 15 const imagePackerApi = image.createImagePacker(); 16 ``` 17 182. 设置编码输出流和编码参数。 19 20 format为图像的编码格式;quality为图像质量,范围从0-100,100为最佳质量。 21 22 ```ts 23 let packOpts : image.PackingOption = { format:"image/jpeg", quality:98 }; 24 ``` 25 263. [创建PixelMap对象或创建ImageSource](image-decoding.md)对象。 27 284. 进行图片编码,并保存编码后的图片。 29 30 方法一:通过PixelMap进行编码。 31 32 ```ts 33 import {BusinessError} from '@ohos.base' 34 imagePackerApi.packing(pixelMap, packOpts).then( (data : ArrayBuffer) => { 35 // data 为打包获取到的文件流,写入文件保存即可得到一张图片 36 }).catch((error : BusinessError) => { 37 console.error('Failed to pack the image. And the error is: ' + error); 38 }) 39 ``` 40 41 方法二:通过imageSource进行编码。 42 43 ```ts 44 import {BusinessError} from '@ohos.base' 45 imagePackerApi.packing(imageSource, packOpts).then( (data : ArrayBuffer) => { 46 // data 为打包获取到的文件流,写入文件保存即可得到一张图片 47 }).catch((error : BusinessError) => { 48 console.error('Failed to pack the image. And the error is: ' + error); 49 }) 50 ``` 51