PixelMap深拷贝案例
介绍
在图片开发过程中经常会涉及到PixelMap的深拷贝,本例通过使用PixelMap的readPixelsToBuffer方法来实现深拷贝。在创建源PixelMap的时候,需要将解码参数设置为BGRA_8888,而在深拷贝创建目标PixelMap的时候需要将解码参数设置为RGBA_8888。详见CopyObj.ets。
效果图预览
使用说明
- 进入页面,显示的即为rawfile中图片的PixelMap经过深拷贝过后的PixelMap对象。点击底部的按钮,对原始PixelMap进行深拷贝后再根据相应的比例进行裁剪。点击顶部的保存图标,可以保存当前图片。
实现思路
- PixelMap深拷贝方法。通过readPixelsToBuffer读取图片资源的PixelMap到ArrayBuffer,再通过createPixelMap得到目标PixelMap。
async function copyPixelMap(pm: PixelMap): Promise<PixelMap> {
const imageInfo: image.ImageInfo = await pm.getImageInfo();
const buffer: ArrayBuffer = new ArrayBuffer(pm.getPixelBytesNumber());
// TODO 知识点:通过readPixelsToBuffer实现PixelMap的深拷贝,其中readPixelsToBuffer输出为BGRA_8888
await pm.readPixelsToBuffer(buffer);
// TODO 知识点:readPixelsToBuffer输出为BGRA_8888,此处createPixelMap需转为RGBA_8888
const opts: image.InitializationOptions = {
editable: true,
pixelFormat: image.PixelMapFormat.RGBA_8888,
size: {
height: imageInfo.size.height, width: imageInfo.size.width }
};
return await image.createPixelMap(buffer, opts);
}
- 初始化时,通过深拷贝从原始PixelMap创建目标PixelMap。源码参考ImageDepthCopy.ets。
async aboutToAppear(): Promise<void> {
const context: Context = getContext(this);
// 获取resourceManager资源管理
const resourceMgr: resourceManager.ResourceManager = context.resourceManager;
// 获取rawfile中的图片资源
const fileData: Uint8Array = await resourceMgr