文档管理中心

使用PixelMap完成图像变换

图片处理指对PixelMap进行相关的操作,如获取图片信息、裁剪、缩放、偏移、旋转、翻转、设置透明度、读写像素数据等。图片处理主要包括图像变换、位图操作,本文介绍图像变换。

开发步骤

图像变换相关API的详细介绍请参见Interface (PixelMap)

  1. 完成图片解码,获取PixelMap对象。

  2. 获取图片信息。

    收起
    自动换行
    深色代码主题
    复制
    1. // 获取图片大小。
    2. await this.pixelMap.getImageInfo().then((info: image.ImageInfo) => {
    3. this.imageInfo = info;
    4. Logger.info('Image width: ', info.size.width.toString());
    5. Logger.info('Image height: ', info.size.height.toString());
    6. }).catch((err: BusinessError) => {
    7. Logger.error('Failed to obtain the image pixel map information. The error is: ', String(err));
    8. });
  3. 进行图像变换操作。

    原图:

    • 裁剪

      收起
      自动换行
      深色代码主题
      复制
      1. const imageInfo = this.pixelMap.getImageInfoSync();
      2. const cropWidth = Math.min(400, imageInfo.size.width); // 原图宽度小于400时防止裁剪区域超出范围。
      3. const cropHeight = Math.min(400, imageInfo.size.height); // 原图高度小于400时防止裁剪区域超出范围。
      4. // x:裁剪起始点横坐标0。
      5. // y:裁剪起始点纵坐标0。
      6. // width:原图宽度不小于400时,裁剪宽度400,方向为从左到右(裁剪后的图片宽度为400)。
      7. // height:原图高度不小于400时,裁剪高度400,方向为从上往下(裁剪后的图片高度为400)。
      8. this.pixelMap.crop({ x: 0, y: 0, size: { width: cropWidth, height: cropHeight } }).then(() => {
      9. // ...
      10. });

    • 缩放

      收起
      自动换行
      深色代码主题
      复制
      1. // 宽为原来的0.5倍。
      2. // 高为原来的0.5倍。
      3. this.pixelMap.scale(0.5, 0.5).then(() => {
      4. // ...
      5. });

    • 平移

      收起
      自动换行
      深色代码主题
      复制
      1. // 向下平移100。
      2. // 向右平移100。
      3. this.pixelMap.translate(100, 100).then(() => {
      4. // ...
      5. });

    • 旋转

      收起
      自动换行
      深色代码主题
      复制
      1. // 顺时针旋转90°。
      2. this.pixelMap.rotate(90).then(() => {
      3. // ...
      4. });

    • 翻转

      收起
      自动换行
      深色代码主题
      复制
      1. // 垂直翻转。
      2. this.pixelMap.flip(false, true).then(() => {
      3. // ...
      4. });

      收起
      自动换行
      深色代码主题
      复制
      1. // 水平翻转。
      2. this.pixelMap.flip(true, false).then(() => {
      3. // ...
      4. });

    • 透明度

      收起
      自动换行
      深色代码主题
      复制
      1. // 将所有像素的透明度改为0.5。
      2. this.pixelMap.opacity(0.5).then(() => {
      3. // ...
      4. });

示例代码

在 指南 中进行搜索
请输入您想要搜索的关键词