HarmonyOS PixelMap裁剪?

想对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的参数以得到正确的裁剪图?

阅读 578
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进