【关键字】
PixelMap / 图片 / 保存 / 闪退
【问题描述】
获取相册图片进行裁剪,完成之后,对图片调用PixelMap进行保存到本地,出现系统闪退。
关键代码如下:
export async function savePixelMapV2(context: Context, pixelMap: PixelMap): Promise<string> {
if (pixelMap === null) {
console.error('传入的pm为空');
return '';
}
const imagePackerApi: image.ImagePacker = image.createImagePacker();
const path: string = context.cacheDir + '/' + getTimeStr() + '.jpg';
const packOpts: image.PackingOption = { format: 'image/jpeg', quality: 100 };
let file = fs.openSync(path, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE);
return await imagePackerApi.packToFile(pixelMap, file.fd, packOpts).then(() => {
//直接打包进文件
fs.closeSync(file.fd);
return " "
}).catch((error: Error) => {
console.error('Failed to pack the image. And the error is: ' + error);
return " "
})
}
.then(() => {
if (this.pixelMap) {
console.debug("savePixelMapV2...")
savePixelMapV2(getContext(this), this.pixelMap)
}
this.flushPixelMapNew();
});
单独的click回调正常执行不会有任何问题。但是在then里面调用savePixelMapV2方法必现崩溃。
【解决方案】
demo如下:
export async function savePixelMapV2(context: Context, pixelMap: PixelMap,width: number, height: number):Promise<string> {
if (pixelMap === null) {
console.error('传入的pm为空');
return '';
}
const imagePackerApi: image.ImagePacker = image.createImagePacker();
const path: string = context.cacheDir + '/' + getTimeStr() + '.jpg';
const packOpts: image.PackingOption = { format: 'image/jpeg', quality: 100 };
let file = fs.openSync(path, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE);
console.log('path:'+path+"--file:"+file.fd)
//该三个参数测试固定为16:9,建议封装调用
const cropWidth = width;
const cropHeight = Math.floor(width * (CommonConstants.CROP_RATE_9_16));
const cropPosition = new RegionItem(0, Math.floor((height - cropHeight) / CommonConstants.AVERAGE_WEIGHT_WIDTH));
//裁切后打包
return pixelMap.crop({
size: {
width: cropWidth,
height: cropHeight
},
x: cropPosition.x,
y: cropPosition.y
}).then(() => {
console.info('Sucessed in cropping pixelmap.');
imagePackerApi.packToFile(pixelMap, file.fd, packOpts)
.then(() => {
console.info('Succeeded in packToFile.');
//直接打包进文件
fs.closeSync(file.fd);
console.debug("path_:" + path)
return ''
}).catch((error : BusinessError) => {
console.error('Failed to packToFile.');
return ''
})
return '';
}).catch((err : BusinessError) => {
console.error('Failed to crop pixelmap.');
return ''
});
}
16:9 方法调用修改部分如下:
case CropType.RECTANGLE:
if (this.pixelMap) {
// rectangle(this.pixelMap, imageWidth, imageHeight)
// .then(() => {
// if (this.pixelMap) {
// console.debug("savePixelMapV2...")
// savePixelMapV2(getContext(this), this.pixelMap)
// }
// this.flushPixelMapNew();
// });
savePixelMapV2(getContext(this),this.pixelMap,imageWidth,imageHeight).then(() => {
this.flushPixelMapNew();
})
}break;