读取PixelMap的ArrayBuffer,再使用读取的数据创建PixelMap,图片变成了黑白,丢失了颜色。
1、读取PixelMap的ArrayBuffer:
async pixelMapToArray(pixelMap:PixelMap){
//size为需要创建的像素buffer大小,取值为:height * width *4
let size = pixelMap.getPixelBytesNumber();
const readBuffer: ArrayBuffer = new ArrayBuffer(size);
if (pixelMap) {
await pixelMap.readPixelsToBuffer(readBuffer);
let bufferSize = readBuffer.byteLength;
return readBuffer;
}
return readBuffer;
}
2、使用读取的数据创建PixelMap:
arrayToPixelMap(readBuffer: ArrayBuffer | null, w:number, h:number, callback:(pixelMap:PixelMap)=>void){
let opts: image.InitializationOptions = { editable: true, pixelFormat: image.PixelMapFormat.RGBA_8888,
size: { height: h, width: w } }
image.createPixelMap(readBuffer, opts).then((pixelMap)=>{
callback(pixelMap);
});
}
3、调用:
PhotoChangeUtils.pixelMapToArray(pixelMap).then((buffer)=>{
let imageInfo = pixelMap.getImageInfoSync();
let w = imageInfo.size.width;
let h = imageInfo.size.height;
PhotoChangeUtils.arrayToPixelMap(buffer, w, h, (pixelMap)=>{
this.livePixelMap = pixelMap;
} )
})
由image.createPixelMap描述可知通过属性创建PixelMap,默认采用BGRA\_8888格式处理数据,通过Promise返回结果,即使创建pixelMap时的buffer和options都是rgba格式的,当前接口只能处理BGRA流,建议尝试统一更改为BGRA\_8888。
参考示例: