项目中有需求要对获取的图片进行压缩,并且是要压缩到固定大小,考虑到harmonyos中对图片质量压缩方式packing,压缩后要及时检查大小,就使用while循环一步步的压缩,直至压缩到目标值
let bitmap: ArrayBuffer;// 需要压缩的数据
let compressSize: number;// 目标大小
let considerBase64: boolean;// 是否考虑base64算法把字节数扩大4/3倍的影响
let result='';
if (bitmap){
try {
let imageSource = image.createImageSource(bitmap);
let packer = image.createImagePacker();
let packerData = await packer.packing(imageSource,{
format: 'image/jpeg'.
quality: 100
}):
if (considerBase64 && compresssize > 0){
compresssize = Math.ceil(compressSize * 3.0 / 4.0 -0.5);
}
let optionQuality = 90:
while (compresssize > 0
&& packerData.byteLength / 1024 > compresssize
&& optionQuality > 0) {
let whilePacker = image.createImagePacker();
let whileImageSource = image.createImageSource(packerData);
packerData = await whilePacker.packing(whileImageSource,{
format: 'image/jpeg',
quality: optionQuality
});
optionQuality -= 10;
}
result = buffer.from(packerData).tostrinl('base64');
} catch (error){
hilog.error(0x0000, 'error: ' + JSOM.stringify(error), '%{public}s');
}
}
----------------- end ---------------
后面会继续补充不足之处。