这里以编码成jpeg图片为例。编码的目标格式format遵循MIME标准定义,因此PackingOption.format应设置为image/jpeg,编码后的文件扩展名可设为.jpg或.jpeg。
图片编码指将Picture对象编码成不同格式的图片文件(当前仅支持编码为JPEG 和 HEIF 格式),用于后续处理,如保存、传输等。
图片编码相关API的详细介绍请参见ImagePacker。
导入相关模块包。
// 导入相关模块。
import { image } from '@kit.ImageKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { common } from '@kit.AbilityKit';
import { fileIo } from '@kit.CoreFileKit';
import { resourceManager } from '@kit.LocalizationKit';设置编码选项PackingOption。
这里以编码成jpeg图片为例。编码的目标格式format遵循MIME标准定义,因此PackingOption.format应设置为image/jpeg,编码后的文件扩展名可设为.jpg或.jpeg。
let packOpts: image.PackingOption = {
format: 'image/jpeg',
// quality默认值为0,建议不低于80;本示例统一设置为90,兼顾图片质量和文件体积。
quality: 90,
needsPackProperties: true
};封装函数,传入picture,使用packing接口编码到ArrayBuffer,或使用packToFile接口编码到文件。
在进行编码前,需要先通过解码获取picture,可参考使用ImageSource完成多图对象解码。
picture编码到ArrayBuffer。
async function packing(picture: image.Picture, packOpts: image.PackingOption) {
const imagePackerApi = image.createImagePacker();
try {
let data = await imagePackerApi.packing(picture, packOpts);
copyData = data;
console.info('Succeeded in packing the image.');
} catch (error) {
console.error('Failed to pack the picture to data. And the error is: ' + error);
} finally {
await imagePackerApi.release();
}
}picture编码到文件。
async function packToFile(picture: image.Picture, packOpts: image.PackingOption, context: Context) {
let imagePackerApi: image.ImagePacker | undefined = undefined;
let file: fileIo.File | undefined = undefined;
try {
const path : string = context.cacheDir + '/picture.jpg';
file = fileIo.openSync(path, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
imagePackerApi = image.createImagePacker();
await imagePackerApi.packToFile(picture, file.fd, packOpts);
} catch (error) {
console.error('Failed to pack the picture to file. And the error is: ' + error);
} finally {
if (file) {
fileIo.closeSync(file.fd);
}
if (imagePackerApi) {
await imagePackerApi.release();
}
}
}合作咨询
我们的专家服务团队将竭诚为您提供专业的合作咨询服务
解决方案
精准高效的一站式服务支持,助力开发者商业成功