在 HarmonyOS 研发过程中,我们经常需要将资源文件转换为 image.PixelMap 对象,以便对图像进行像素级的编辑、缩放或绘制等操作。由于系统未提供从资源直接转为可编辑 PixelMap 的方法,开发者通常需要自行封装转换逻辑。
以下代码示例展示了如何将资源文件转换为支持二次编辑的 PixelMap对象,并提供了详细注释说明每一步的作用:
/**
* 将资源文件转换为可编辑的 image.PixelMap 对象
* @param resource 资源管理器中的资源引用,如 $r('app.media.image')
* @param context 上下文对象,用于获取 ResourceManager
* @returns 返回可用于图像编辑的 PixelMap 对象
*/
function resImageToImagePixelMap(resource: Resource, context: Context): image.PixelMap {
// 获取资源的二进制数据
const data: Uint8Array = context.resourceManager.getMediaContentSync(resource) as Uint8Array;
// 将 Uint8Array 转为 ArrayBuffer,确保数据格式兼容
const arrayBuffer: ArrayBuffer = data.buffer.slice(data.byteOffset, data.byteLength + data.byteOffset);
// 创建 ImageSource 对象,用于解码图像
const imageSource: image.ImageSource = image.createImageSource(arrayBuffer);
// 同步获取原图像基本信息,用于生成pixelMap对像
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 }
};
// 生成并返回 PixelMap 对象
const pixelMap: PixelMap = imageSource.createPixelMapSync(options);
return pixelMap;
}使用示例如下:
// 传入资源文件,及上下文
let imagePixelMap = resImageToImagePixelMap($r('app.media.image'), context);接下来,就可以直接对imagePixelMap进行编缉的操作了。

















