HarmonyOS 鸿蒙Next 相册图片选择压缩报错
HarmonyOS 鸿蒙Next 相册图片选择压缩报错
选择相册中照片,然后压缩处理。createImageSource一直失败,导致不能压缩。 请问压缩需要配置什么特殊的权限吗?
// 创建图片选择器
let photoPicker = new photoAccessHelper.PhotoViewPicker();
// 打开相册选择图片
let result = await photoPicker.select({
isEditSupported: true,
isOriginalSupported: true,
maxSelectNumber: 9,
MIMEType: photoAccessHelper.PhotoViewMIMETypes.IMAGE_VIDEO_TYPE
});
// 检查是否选择了图片
if (result && result.photoUris && result.photoUris.length > 0) {
const uri = result.photoUris[0]; // 获取第一张图片的 URI
HtLogUtil.info(TAG, '选择的图片 URI: ', uri);
try {
// 检查文件是否存在
fs.accessSync(uri);
HtLogUtil.info(TAG, '文件存在');
// 创建 ImageSource
const imageSourceApi: image.ImageSource = image.createImageSource(uri);
if (!imageSourceApi) {
throw new Error('ImageSource 创建失败,URI 可能无效');
}
// 获取图片信息,确保 ImageSource 有效
const imageInfo: image.ImageInfo = await imageSourceApi.getImageInfo();
HtLogUtil.info(TAG, '图片信息: ', JSON.stringify(imageInfo));
// 设置压缩选项
let packOpts: image.PackingOption = { format: "image/jpeg", quality: 98 }; // 压缩为 JPEG 格式,质量为 98
// 定义压缩后的文件路径
const filePath: string = getContext().filesDir + "/compressed_image.jpg";
// 创建文件
let file = fs.openSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE);
// 创建 ImagePacker
const imagePackerApi: image.ImagePacker = image.createImagePacker();
// 压缩图片并保存到文件
await imagePackerApi.packToFile(imageSourceApi, file.fd, packOpts);
HtLogUtil.info(TAG, '图片压缩成功,保存路径: ', filePath);
// 关闭文件
fs.closeSync(file);
} catch (error) {
HtLogUtil.error(TAG, '图片压缩失败: ', error.message);
}
} else {
HtLogUtil.error(TAG, '未选择图片或图片 URI 无效');
}
更多关于HarmonyOS 鸿蒙Next 相册图片选择压缩报错的实战教程也可以访问 https://www.itying.com/category-93-b0.html
createImageSource接口当前仅支持应用沙箱路径,传uri是不行的。
解决方案:
-
将图片复制一份到应用沙箱中,获取到该图片应用沙箱的路径再调用createImageSource(uri)
-
还可以通过image.createImageSource(fd),通过传入文件描述符来创建图片源实例,参考如下:
//获取文件
let file = fileIo.openSync(this.imageWaterMaskUri, fileIo.OpenMode.READ_ONLY)
//通过传入文件描述符来创建图片源实例
let imageSource: image.ImageSource = image.createImageSource(file.fd);
或者你也可以参考图片压缩方案的demo:https://gitee.com/harmonyos-cases/cases/blob/master/CommonAppDevelopment/feature/imagecompression/README.md
更多关于HarmonyOS 鸿蒙Next 相册图片选择压缩报错的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
针对HarmonyOS 鸿蒙Next系统中相册图片选择后进行压缩时出现的报错问题,可能的原因及解决方案如下:
-
权限问题:
- 确保应用已正确申请并获得了访问相册和读写存储的权限。
- 检查是否在运行时动态申请了权限,并正确处理了用户拒绝授权的情况。
-
图片路径或文件访问问题:
- 确认选择的图片路径是否正确,以及应用是否有权限访问该路径。
- 检查文件是否存在,以及是否因为文件被其他应用占用而导致无法读取。
-
压缩算法或库的问题:
- 检查使用的压缩算法或第三方库是否兼容HarmonyOS系统。
- 尝试更新或更换压缩库,以确保其稳定性和兼容性。
-
系统Bug或版本问题:
- 确认是否为HarmonyOS系统的已知Bug,可查阅官方论坛或更新日志。
- 尝试更新系统到最新版本,看是否能解决问题。
如果上述方法均未能解决问题,可能是更深层次的系统或应用兼容性问题。此时,建议直接联系官网客服获取更专业的技术支持。官网地址是:https://www.itying.com/category-93-b0.html