//打开相册选择图片完成
let PhotoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
PhotoSelectOptions.MIMEType = 'image/*';
PhotoSelectOptions.maxSelectNumber = 9;
let photoPicker = new photoAccessHelper.PhotoViewPicker();
//打开相册
photoPicker.select(PhotoSelectOptions).then((PhotoSelectResult: photoAccessHelper.PhotoSelectResult) => {
//处理返回结果,获取uri,转换为base64字符串
PhotoSelectResult.photoUris.forEach((uri,index)=>{
this.packageImage(uri,80).then(()=>{})
})
})
//uri:相册图片uri, precent:压缩系数
packageImage(uri: string, precent: number): Promise<BOBSelectImageModel> {
return new Promise<BOBSelectImageModel>((resolve, reject) => {
let selectModel = new BOBSelectImageModel()
const imagePackerApi: image.ImagePacker = image.createImagePacker();
let file = fileIo.openSync(uri, fileIo.OpenMode.READ_ONLY);
const imageSourceApi: image.ImageSource = image.createImageSource(file.fd);
let comNum = Math.trunc(precent)
let packOpts: image.PackingOption = { format: "image/jpeg", quality: comNum }
imagePackerApi.packing(imageSourceApi, packOpts).then((data: ArrayBuffer) => {
if (data.byteLength > 0) {
let base64Str = buffer.from(data).toString('base64')
let resultBase64Str = base64Str ? base64Str : ''
BoBLog.debug('', 'resultBase64Str长度-=======+++====' + resultBase64Str.length);
selectModel.PhotoImg = resultBase64Str
selectModel.precent = 0
fileIo.close(file.fd,(err: BusinessError) => {
if (err) {
console.error("close file failed with error message: " + err.message + ", error code: " + err.code);
} else {
console.info("close file succeed");
}
})
resolve(selectModel)
} else {
// fileIo.closeSync(file.fd);
selectModel.precent = 1
resolve(selectModel)
}
})
})
}
多次调用上述压缩方法packageImage,内存会持续增加,最后导致闪退。fileIo.close关闭打印日志为成功。该方法压缩图片方式是否存在问题。有无解决方法
解决方案
该方法可以正常处理压缩图片,建议使用release方法释放当前实例对象。用法参考文档:
https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-image-V5\#release7
如果想进一步提升查找性能,可以使用二分查找最接近指定图片压缩目标大小的图片质量quality来压缩图片,示例参考:
https://gitee.com/harmonyos-cases/cases/tree/master/CommonAppDevelopment/feature/imagecompression\#%E9%AB%98%E6%80%A7%E8%83%BD%E7%9F%A5%E8%AF%86%E7%82%B9