【鸿蒙】【毛豆工具集】【图片】将资源文件转为image.PixelMap对像

22 阅读1分钟

在研发过程中,需要将资源文件转为image.PixelMap进行二次编辑,系统没有提供直接的转换方法,需要进行二次封装,代码如下:

function resImageToImagePixelMap(resource: Resource, context: Context): image.PixelMap {
  const data: Uint8Array = context.resourceManager.getMediaContentSync(resource) as Uint8Array;
  const arrayBuffer: ArrayBuffer = data.buffer.slice(data.byteOffset, data.byteLength + data.byteOffset);
  const imageSource: image.ImageSource = image.createImageSource(arrayBuffer);
  const imageInfo: image.ImageInfo = imageSource.getImageInfoSync();
  const height = imageInfo.size.height;
  const width = imageInfo.size.width;
  const options: image.DecodingOptions = {
    editable: true,
    desiredSize: { height, width }
  };
  const pixelMap: PixelMap = imageSource.createPixelMapSync(options);
  return pixelMap;
}

使用示例如下:

let imagePixelMap = resImageToImagePixelMap($r('app.media.image'), context);