位图操作

2024-02-16 13:59 更新

当需要对目标图片中的部分区域进行处理时,可以使用位图操作功能。此功能常用于图片美化等操作。

如下图所示,一张图片中,将指定的矩形区域像素数据读取出来,进行修改后,再写回原图片对应区域。

图1 位图操作示意图

开发步骤

位图操作相关API的详细介绍请参见API参考

  1. 完成图片解码,获取PixelMap位图对象。
  2. 从PixelMap位图对象中获取信息。

    1. // 获取图像像素的总字节数
    2. let pixelBytesNumber = pixelMap.getPixelBytesNumber();
    3. // 获取图像像素每行字节数
    4. let rowCount = pixelMap.getBytesNumberPerRow();
    5. // 获取当前图像像素密度。像素密度是指每英寸图片所拥有的像素数量。像素密度越大,图片越精细。
    6. let getDensity = pixelMap.getDensity();
  3. 读取并修改目标区域像素数据,写回原图。
    1. // 场景一:将读取的整张图像像素数据结果写入ArrayBuffer
    2. const readBuffer = new ArrayBuffer(pixelBytesNumber);
    3. pixelMap.readPixelsToBuffer(readBuffer).then(() => {
    4. console.info('Succeeded in reading image pixel data.');
    5. }).catch(error => {
    6. console.error('Failed to read image pixel data. And the error is: ' + error);
    7. })
    8. // 场景二:读取指定区域内的图片数据,结果写入area.pixels中
    9. const area = {
    10. pixels: new ArrayBuffer(8),
    11. offset: 0,
    12. stride: 8,
    13. region: { size: { height: 1, width: 2 }, x: 0, y: 0 }
    14. }
    15. pixelMap.readPixels(area).then(() => {
    16. console.info('Succeeded in reading the image data in the area.');
    17. }).catch(error => {
    18. console.error('Failed to read the image data in the area. And the error is: ' + error);
    19. })
    20. // 对于读取的图片数据,可以独立使用(创建新的pixelMap),也可以对area.pixels进行所需修改
    21. // 将图片数据area.pixels写入指定区域内
    22. pixelMap.writePixels(area).then(() => {
    23. console.info('Succeeded to write pixelMap into the specified area.');
    24. })
    25. // 将图片数据结果写入pixelMap中
    26. const writeColor = new ArrayBuffer(96);
    27. pixelMap.writeBufferToPixels(writeColor, () => {});
以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号