1# 图片编码(ArkTS) 2 3图片编码指将PixelMap编码成不同格式的存档图片(当前仅支持打包为JPEG、WebP 和 png 格式),用于后续处理,如保存、传输等。 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 '@ohos.multimedia.image'; 16 17 const imagePackerApi = image.createImagePacker(); 18 ``` 19 202. 设置编码输出流和编码参数。 21 22 format为图像的编码格式;quality为图像质量,范围从0-100,100为最佳质量。 23 24 ```ts 25 let packOpts : image.PackingOption = { format:"image/jpeg", quality:98 }; 26 ``` 27 283. [创建PixelMap对象或创建ImageSource](image-decoding.md)对象。 29 304. 进行图片编码,并保存编码后的图片。 31 32 方法一:通过PixelMap进行编码。 33 34 ```ts 35 import {BusinessError} from '@ohos.base' 36 imagePackerApi.packing(pixelMap, packOpts).then( (data : ArrayBuffer) => { 37 // data 为打包获取到的文件流,写入文件保存即可得到一张图片 38 }).catch((error : BusinessError) => { 39 console.error('Failed to pack the image. And the error is: ' + error); 40 }) 41 ``` 42 43 方法二:通过imageSource进行编码。 44 45 ```ts 46 import {BusinessError} from '@ohos.base' 47 imagePackerApi.packing(imageSource, packOpts).then( (data : ArrayBuffer) => { 48 // data 为打包获取到的文件流,写入文件保存即可得到一张图片 49 }).catch((error : BusinessError) => { 50 console.error('Failed to pack the image. And the error is: ' + error); 51 }) 52 ``` 53 54### 图片编码进文件 55 56在编码时,开发者可以传入对应的文件路径,编码后的内存数据将直接写入文件。 57 58 方法一:通过PixelMap编码进文件。 59 60 ```ts 61 import {BusinessError} from '@ohos.base' 62 import fs from '@ohos.file.fs' 63 const context : Context = getContext(this); 64 const path : string = context.cacheDir + "/pixel_map.jpg"; 65 let file = fs.openSync(path, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE); 66 imagePackerApi.packToFile(pixelMap, file.fd, packOpts).then(() => { 67 // 直接打包进文件 68 }).catch((error : BusinessError) => { 69 console.error('Failed to pack the image. And the error is: ' + error); 70 }) 71 ``` 72 73 方法二:通过imageSource编码进文件。 74 75 ```ts 76 import {BusinessError} from '@ohos.base' 77 import fs from '@ohos.file.fs' 78 const context : Context = getContext(this); 79 const filePath : string = context.cacheDir + "/image_source.jpg"; 80 let file = fs.openSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE); 81 imagePackerApi.packToFile(imageSource, file.fd, packOpts).then(() => { 82 // 直接打包进文件 83 }).catch((error : BusinessError) => { 84 console.error('Failed to pack the image. And the error is: ' + error); 85 }) 86 ``` 87