1# 位图操作 2 3当需要对目标图片中的部分区域进行处理时,可以使用位图操作功能。此功能常用于图片美化等操作。 4 5如下图所示,一张图片中,将指定的矩形区域像素数据读取出来,进行修改后,再写回原图片对应区域。 6 7**图1** 位图操作示意图 8 9 10## 开发步骤 11 12位图操作相关API的详细介绍请参见[API参考](../reference/apis/js-apis-image.md#pixelmap7)。 13 141. 完成[图片解码](image-decoding.md#开发步骤),获取PixelMap位图对象。 15 162. 从PixelMap位图对象中获取信息。 17 18 ```ts 19 import image from '@ohos.multimedia.image'; 20 // 获取图像像素的总字节数 21 let pixelBytesNumber : number = pixelMap.getPixelBytesNumber(); 22 // 获取图像像素每行字节数 23 let rowCount : number = pixelMap.getBytesNumberPerRow(); 24 // 获取当前图像像素密度。像素密度是指每英寸图片所拥有的像素数量。像素密度越大,图片越精细。 25 let getDensity : number = pixelMap.getDensity(); 26 ``` 27 283. 读取并修改目标区域像素数据,写回原图。 29 30 ```ts 31 import {BusinessError} from '@ohos.base' 32 // 场景一:将读取的整张图像像素数据结果写入ArrayBuffer中 33 const readBuffer = new ArrayBuffer(pixelBytesNumber); 34 pixelMap.readPixelsToBuffer(readBuffer).then(() => { 35 console.info('Succeeded in reading image pixel data.'); 36 }).catch((error : BusinessError) => { 37 console.error('Failed to read image pixel data. And the error is: ' + error); 38 }) 39 40 // 场景二:读取指定区域内的图片数据,结果写入area.pixels中 41 const area : image.PositionArea = { 42 pixels: new ArrayBuffer(8), 43 offset: 0, 44 stride: 8, 45 region: { size: { height: 1, width: 2 }, x: 0, y: 0 } 46 } 47 pixelMap.readPixels(area).then(() => { 48 console.info('Succeeded in reading the image data in the area.'); 49 }).catch((error : BusinessError) => { 50 console.error('Failed to read the image data in the area. And the error is: ' + error); 51 }) 52 53 // 对于读取的图片数据,可以独立使用(创建新的pixelMap),也可以对area.pixels进行所需修改 54 // 将图片数据area.pixels写入指定区域内 55 pixelMap.writePixels(area).then(() => { 56 console.info('Succeeded to write pixelMap into the specified area.'); 57 }) 58 59 // 将图片数据结果写入pixelMap中 60 const writeColor = new ArrayBuffer(96); 61 pixelMap.writeBufferToPixels(writeColor, () => {}); 62 ``` 63