想对PixelMap进行裁剪,直接调用其crop方法固然可以,但是这会在原PixelMap上操作,想要的是生成一个全新的PixelMap对象。
已实现有2种方案:
方案一:先复制PixelMap,在PixelMap副本上调用crop:
// 复制PixelMap方法
export async function copyPixelMap(pixelMap: PixelMap) {
const imageInfo: image.ImageInfo = await pixelMap.getImageInfo()
const buffer: ArrayBuffer = new ArrayBuffer(pixelMap.getPixelBytesNumber())
await pixelMap.readPixelsToBuffer(buffer)
const initOpts: image.InitializationOptions = {
editable: true,
pixelFormat: image.PixelMapFormat.RGBA_8888,
size: {
width: imageInfo.size.width,
height: imageInfo.size.height
}
}
return await image.createPixelMap(buffer, initOpts)
}
// 裁剪PixelMap方法
export async function cropPixelMap(pixelMap: PixelMap, x: number, y: number, width: number, height: number) {
// 复制原图
const tmp: PixelMap = await copyPixelMap(pixelMap)
// 裁剪区域
const regin: image.Region = {
x: x,
y: y,
size: {
width: width,
height: height,
}
}
await tmp.crop(regin)
return tmp
}
此方法存在如下弊端:
- 将原图多复制了一份,内存占用稍多了一些。
- 属于取巧的方法,调用副本PixelMap的crop方法,并不是直接的裁剪图片,有点绕弯子。
- 可能PixelMapFormat设置有问题,裁剪得到的图片偏蓝色,像是被加了滤镜。这个方案,如何使得得到的裁剪图颜色正常?
方案二:先通过readPixels(area: PositionArea)读取待裁剪区域像素数据,再调用image.createPixelMap生成PixelMap:
export async function cropPixelMap(pixelMap: PixelMap, x: number, y: number, width: number, height: number) {
const area: image.PositionArea ={
pixels: new ArrayBuffer(pixelMap.getPixelBytesNumber()),
offset: 0,
stride: pixelMap.getBytesNumberPerRow(),
region: {
x: x,
y: y,
size: {
width: width,
height: height
}
}
}
await pixelMap.readPixels(area)
const initOpt:image.InitializationOptions = {
editable: true,
pixelFormat: image.PixelMapFormat.RGBA_8888,
size: {
width: width,
height: height
}
}
return await image.createPixelMap(area.pixels, initOpt)
}
此方法存在如下问题:
- PositionArea 内的参数设定应该有问题,如何设定。
- 裁剪得到的图片是乱码。这个方案,如何正确设定PositionArea的参数以得到正确的裁剪图?
这个方案,如何正确设定PositionArea的参数以得到正确的裁剪图?
方案一:首先,copy前先确认下源pixelmap的格式:https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-image-V5\#ZH-CN\_TOPIC\_0000001884758670\_\_getimageinfosync12
方法1:https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-image-V5\#initializationoptions8
方法2:readpixelmaptobuffer拿到的BGRA\_8888,可以抽个方法把[[b,g,r,a]…] 转换成[[r,g,b,a]…]。
方案二 :readPixels参数设置参考:https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-sendableimage-V5\#readpixels
https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-image-V5\#positionarea7
图片剪裁可以参考完整demo,地址如下:https://developer.huawei.com/consumer/cn/codelabsPortal/carddetails/tutorials\_NEXT-ImageEdit