如果你也对鸿蒙开发感兴趣,加入“Harmony自习室”吧!扫描下方名片,关注公众号,公众号更新更快,同时也有更多学习资料和技术讨论群。

1、概述
图片处理指对PixelMap进行相关的操作,如获取图片信息、裁剪、缩放、偏移、旋转、翻转、设置透明度、读写像素数据等。图片处理主要包括图像变换、位图操作。
需要注意的是,本文是接续鸿蒙媒体开发系列15——图片解码(PixcelMap)的内容。后文所有的讨论就基于PixcelMap实例来操作。
2、图像变换
本文中讨论的原图如下:

👉🏻 获取图片信息
// 获取图片大小pixelMap.getImageInfo().then( info => {console.info('info.width = ' + info.size.width);console.info('info.height = ' + info.size.height);}).catch((err) => {console.error("Failed to obtain the image pixel map information.And the error is: " + err);});
图片info信息结构如下:

👉🏻 裁剪图片
// x: 裁剪起始点横坐标0// y: 裁剪起始点纵坐标0// height: 裁剪高度400,方向为从上往下(裁剪后的图片高度为400)// width: 裁剪宽度400,方向为从左到右(裁剪后的图片宽度为400)pixelMap.crop({ x: 0, y: 0, size: { height: 400, width: 400 } });
crop()方法接受的入参数据结构定义如下:

原图裁剪后的图如下:

👉🏻 缩放
// 宽为原来的0.5// 高为原来的0.5pixelMap.scale(0.5, 0.5);

👉🏻 偏移
// 向下偏移100// 向右偏移100pixelMap.translate(100, 100);

👉🏻 旋转
// 顺时针旋转90°pixelMap.rotate(90);

👉🏻 垂直翻转
// 垂直翻转pixelMap.flip(false, true);

👉🏻 水平翻转
// 水平翻转pixelMap.flip(true, false);

👉🏻 设置透明度
// 透明度0.5pixelMap.opacity(0.5);

3、位图操作
当我们需要对目标图片中的部分区域进行处理时,可以使用位图操作功能。此功能常用于图片美化等场景。
如下图所示,一张图片中,将指定的矩形区域像素数据读取出来,进行修改后,再写回原图片对应区域。

读取并修改目标区域像素数据,并写回原图的代码如下:
// 获取图像像素的总字节数let pixelBytesNumber = pixelMap.getPixelBytesNumber();// 获取图像像素每行字节数let rowCount = pixelMap.getBytesNumberPerRow();// 获取当前图像像素密度。像素密度是指每英寸图片所拥有的像素数量。像素密度越大,图片越精细。let getDensity = pixelMap.getDensity();// 场景一:将读取的整张图像像素数据结果写入ArrayBuffer中const readBuffer = new ArrayBuffer(pixelBytesNumber);pixelMap.readPixelsToBuffer(readBuffer).then(() => {console.info('Succeeded in reading image pixel data.');}).catch(error => {console.error('Failed to read image pixel data. And the error is: ' + error);})// 场景二:读取指定区域内的图片数据,结果写入area.pixels中const area = {pixels: new ArrayBuffer(8),offset: 0,stride: 8,region: { size: { height: 1, width: 2 }, x: 0, y: 0 }}pixelMap.readPixels(area).then(() => {console.info('Succeeded in reading the image data in the area.');}).catch(error => {console.error('Failed to read the image data in the area. And the error is: ' + error);})// 对于读取的图片数据,可以独立使用(创建新的pixelMap),也可以对area.pixels进行所需修改// 将图片数据area.pixels写入指定区域内pixelMap.writePixels(area).then(() => {console.info('Succeeded to write pixelMap into the specified area.');})// 将图片数据结果写入pixelMap中const writeColor = new ArrayBuffer(96);pixelMap.writeBufferToPixels(writeColor, () => {});


















