一、背景说明

HarmonyOS 开发者套件 26.0.1 Release 近日发布,ArkUI 新增预加载 NavDestination 页面等能力,而应用内最常见的图片处理需求——解码显示、裁剪缩放、压缩保存——则由 Image Kit(@kit.ImageKit)提供。本文聚焦一个具体技术点:使用 Image Kit 实现图片从解码(ImageSource → PixelMap)、变换编辑(裁剪/缩放/旋转/翻转/透明度)到编码保存(ImagePacker)的完整闭环,全部代码可直接编译运行(本文源码已在 AtomGit 仓库开源,见文末)。

二、技术原理

Image Kit 是鸿蒙的图片处理服务套件,提供图片解码、编辑处理、编码的全流程能力,核心概念:

  • ImageSource(图片源):通过 image.createImageSource(path/uri/fd) 从文件、资源或像素数据创建,调用 createPixelMap() 解码出位图。
  • PixelMap(位图):图片像素对象,支持裁剪(crop)、缩放(scale)、平移(translate)、旋转(rotate)、翻转(flip)、设置透明度(opacity)等操作,操作时坐标系原点为左上角;可直接传给 Image 组件显示。
  • ImagePacker(编码器):通过 image.createImagePacker() 创建,pack() 将 PixelMap 或 ImageSource 编码为指定格式的文件(JPEG、WebP、PNG、HEIC 等)。
  • 内存约束:PixelMap 序列化大小上限 128MiB(宽 × 高 × 每像素字节数);PixelMap 通过 Worker/TaskPool 跨线程传输后,原线程的所有接口不能再调用。

数据流:createImageSource(路径) → createPixelMap(解码) → crop/scale/rotate/flip(变换) → createImagePacker → pack(编码保存) → release 释放。

三、实现步骤

工程为 Stage 模型(API 12+),在 entry/src/main/resources/rawfile/ 下预置一张 test.jpg 测试图片。

1. 图片编辑管理类 ImageEditor.ets
import { image } from '@kit.ImageKit';
import { fileIo as fs } from '@kit.CoreFileKit';
import { common } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

export class ImageEditor {
  private pixelMap: image.PixelMap | undefined;
  private context: common.UIAbilityContext | undefined;

  constructor(context: common.UIAbilityContext) {
    this.context = context;
  }

  // 第一步:解码——从 rawfile 资源创建 ImageSource 并解码为 PixelMap
  async loadFromResource(fileName: string): Promise<void> {
    const resourceMgr = this.context!.resourceManager;
    const rawFile = await resourceMgr.getRawFd(fileName);
    const imageSource: image.ImageSource = image.createImageSource(rawFile);
    // 解码参数:RGBA_8888 像素格式 + 可编辑 + 期望尺寸
    const decodingOptions: image.DecodingOptions = {
      editable: true,
      desiredPixelFormat: image.PixelMapFormat.RGBA_8888
    };
    this.pixelMap = await imageSource.createPixelMap(decodingOptions);
    await imageSource.release(); // ImageSource 用完即释放
  }

  // 第二步:获取图片信息
  async getImageSize(): Promise<image.Size> {
    const info = await this.pixelMap!.getImageInfo();
    return info.size;
  }

  // 第三步:裁剪(坐标原点为左上角,需防止越界)
  async crop(width: number, height: number): Promise<void> {
    const imageInfo = await this.pixelMap!.getImageInfo();
    const cropWidth = Math.min(width, imageInfo.size.width);
    const cropHeight = Math.min(height, imageInfo.size.height);
    await this.pixelMap!.crop({ x: 0, y: 0, size: { width: cropWidth, height: cropHeight } });
  }

  // 第四步:缩放(宽高均为原来的 0.5 倍)
  async scale(ratio: number): Promise<void> {
    await this.pixelMap!.scale(ratio, ratio);
  }

  // 第五步:旋转(顺时针 90°)
  async rotate(deg: number): Promise<void> {
    await this.pixelMap!.rotate(deg);
  }

  // 第六步:翻转(水平 / 垂直)
  async flip(horizontal: boolean, vertical: boolean): Promise<void> {
    await this.pixelMap!.flip(horizontal, vertical);
  }

  // 第七步:设置透明度(0-1)
  async setOpacity(opacity: number): Promise<void> {
    await this.pixelMap!.opacity(opacity);
  }

  // 第八步:编码保存——将 PixelMap 压缩为 JPEG 写入沙箱
  async saveToSandbox(fileName: string, quality: number): Promise<string> {
    if (this.pixelMap === undefined) {
      throw new Error('pixelMap not loaded');
    }
    const packer: image.ImagePacker = image.createImagePacker();
    const packOpts: image.PackingOption = { format: 'image/jpeg', quality: quality };
    const buf = await packer.packToData(this.pixelMap, packOpts);
    await packer.release();

    const filePath = this.context!.filesDir + '/' + fileName;
    const file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
    fs.writeSync(file.fd, buf);
    fs.closeSync(file);
    return filePath;
  }
}

// 补充导入(置于文件头部)
import { fileIo as fs } from '@kit.CoreFileKit';
2. UI 调用示例 Index.ets
import { common } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { ImageEditor } from '../model/ImageEditor';

@Entry
@Component
struct Index {
  @State imagePath: string = '';
  @State imageSize: string = '';
  private editor: ImageEditor = new ImageEditor(getContext(this) as common.UIAbilityContext);

  build() {
    Column({ space: 12 }) {
      Text('Image Kit 图片编辑').fontSize(16).fontWeight(FontWeight.Bold)

      Row({ space: 12 }) {
        Button('加载图片').onClick(async () => {
          try {
            await this.editor.loadFromResource('test.jpg');
            const size = await this.editor.getImageSize();
            this.imageSize = `${size.width} × ${size.height}`;
          } catch (err) {
            this.imageSize = `加载失败 code=${(err as BusinessError).code}`;
          }
        })

        Button('裁剪 400×400').onClick(async () => {
          try {
            await this.editor.crop(400, 400);
            this.imageSize = '已裁剪 400×400';
          } catch (err) {
            this.imageSize = `裁剪失败 code=${(err as BusinessError).code}`;
          }
        })

        Button('缩小 50%').onClick(async () => {
          try {
            await this.editor.scale(0.5);
            this.imageSize = '已缩小 50%';
          } catch (err) {
            this.imageSize = `缩放失败 code=${(err as BusinessError).code}`;
          }
        })

        Button('旋转 90°').onClick(async () => {
          try {
            await this.editor.rotate(90);
            this.imageSize = '已旋转 90°';
          } catch (err) {
            this.imageSize = `旋转失败 code=${(err as BusinessError).code}`;
          }
        })
      }

      Row({ space: 12 }) {
        Button('水平翻转').onClick(async () => {
          await this.editor.flip(true, false);
        })

        Button('透明度 50%').onClick(async () => {
          await this.editor.setOpacity(0.5);
        })

        Button('保存 JPEG').onClick(async () => {
          try {
            const path = await this.editor.saveToSandbox('edited.jpg', 98);
            this.imagePath = path;
          } catch (err) {
            this.imagePath = `保存失败 code=${(err as BusinessError).code}`;
          }
        })
      }

      Text(`尺寸:${this.imageSize}`)
      Text(`路径:${this.imagePath}`)
    }
    .width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }
}
四、应用场景示例

从图库选择图片并加载编辑——结合 PhotoViewPicker 拉起系统相册:

import { photoAccessHelper } from '@kit.MediaLibraryKit';

const picker = new photoAccessHelper.PhotoViewPicker();
const options: photoAccessHelper.PhotoSelectOptions = {
  MIMEType: photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE,
  maxSelectNumber: 1
};
picker.select(options).then(async (res: photoAccessHelper.PhotoSelectResult) => {
  if (res.photoUris.length > 0) {
    await this.editor.loadFromUri(res.photoUris[0]);
  }
});
五、技术要点
1. PixelMap 序列化上限 128MiB

PixelMap 大小计算方式为:宽 × 高 × 每像素占用字节数(如 RGBA_8888 为 4 字节),序列化大小最大为 128MiB,超过会渲染失败。处理大图前应先计算并控制目标尺寸。

2. 跨线程传输后原线程不可用

PixelMap 从 API version 11 开始支持通过 Worker 或 TaskPool 跨线程调用。注意:当 PixelMap 通过 Worker 或 TaskPool 跨线程传输后,原线程的 PixelMap 的所有接口均不能继续调用,否则会抛出 501 或 7600106 错误。

3. 错误处理
try {
  await this.editor.saveToSandbox('out.jpg', 98);
} catch (err) {
  const e = err as BusinessError;
  if (e.code === 62980096) {
    console.error('操作失败:内存不足或上传异常');
  } else if (e.code === 62980119) {
    console.error('图片编码失败');
  } else {
    console.error(`image error code=${e.code}`);
  }
}
六、扩展建议
  1. ImageEffect 滤镜:Image Kit 内置滤镜效果能力,可为图片添加风格化滤镜;
  2. EXIF 信息读取:支持读取和编辑图片 EXIF 信息(光圈、焦距、经纬度等);
  3. WebP 格式支持:ImagePacker 支持 JPEG、WebP、PNG、HEIC、GIF 等格式,按需选择压缩率与质量。
结语

本文用 Image Kit 完成了图片从解码、变换编辑到编码保存的完整实现,核心代码约 150 行,均已开源到文末 AtomGit 仓库。理解 PixelMap 的生命周期与内存约束后,图片编辑类应用的变换操作就能稳定落地。

代码仓库

本文完整工程已在 AtomGit 开源:https://atomgit.com/NJPJI_Yang/hm-article-20261202-image-kit-atomgit

仓库包含可直接用 DevEco Studio 打开编译的完整鸿蒙 Stage 工程(AppScope 应用配置、entry 模块、hvigor 构建脚本齐全),以及与 CSDN 发布内容一致的 article.md 全文。

Logo

作为“人工智能6S店”的官方数字引擎,为AI开发者与企业提供一个覆盖软硬件全栈、一站式门户。

更多推荐