一、背景说明

头像裁剪、缩略图生成、图片压缩上传、旋转矫正——这类"真正改变像素数据"的图片处理,不能靠 Image 组件的 UI 属性(那只是渲染效果,不会修改 PixelMap 数据)。HarmonyOS 的 Image Kit(@kit.ImageKit)提供了图片全生命周期处理能力:ImageSource 解码、PixelMap 像素级编辑(裁剪/缩放/旋转/翻转)、ImagePacker 编码落盘。本文以"选图 → 裁剪 → 缩放 → 保存到沙箱"完整链路为例,实现图片编辑的核心闭环,代码基于 API 12 及以上(含 26.0.x)。

二、技术原理

Image Kit 的处理管线分三级:

  1. 解码(ImageSource):image.createImageSource(fd 或 ArrayBuffer) 从文件/内存创建解码源,createPixelMap(decodingOptions) 解码为 PixelMap;DecodingOptions 的 editable: true 是后续编辑的前提(默认 false 时 crop 等编辑操作会失败),还支持 desiredSize 指定解码尺寸(大图降采样省内存);
  2. 编辑(PixelMap):crop(裁剪,Region 像素坐标)、scale(缩放,参数是目标像素尺寸而非比例)、rotate(旋转,顺时针角度)、flip(翻转)、opacity(透明度),均为就地修改原 PixelMap;需要保留原图时先 copyPixelMap() 出副本;用完调用 release() 释放,避免内存峰值;
  3. 编码(ImagePacker):image.createImagePacker().packing(pixelMap, { format: 'image/jpeg', quality }) 输出 ArrayBuffer,或 packToFile 直接写文件描述符;quality 仅对 JPEG 生效。
三、实现步骤

无需申请任何权限(读取用户相册图片走 picker,图片随 picker 授权返回临时访问权)。工程要求 Stage 模型、API 12 及以上。

1. 图片处理工具类 entry/src/main/ets/image/ImageEditor.ets(完整代码):

import { image } from '@kit.ImageKit';
import { fileIo as fs } from '@kit.CoreFileKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { hilog } from '@kit.PerformanceAnalysisKit';

const TAG: string = 'ImageEditor';

export class ImageEditor {
  // 从 picker 返回的 uri 加载"可编辑"的 PixelMap
  static async loadEditable(uri: string):
    Promise<image.PixelMap | null> {
    const file = fs.openSync(uri, fs.OpenMode.READ_ONLY);
    try {
      const source: image.ImageSource = image.createImageSource(file.fd);
      // editable: true 是关键,否则 crop 等编辑操作将失败
      const options: image.DecodingOptions = { editable: true };
      return await source.createPixelMap(options);
    } catch (err) {
      const e: BusinessError = err as BusinessError;
      hilog.error(TAG, 'load failed: %{public}d', e.code);
      return null;
    } finally {
      fs.closeSync(file);
    }
  }

  // 裁剪:区域为像素坐标(越界会失败,需先做边界检查)
  static async crop(pixelMap: image.PixelMap,
    x: number, y: number, w: number, h: number): Promise<void> {
    const region: image.Region = { x: x, y: y,
      size: { width: w, height: h } };
    await pixelMap.crop(region);   // 就地修改原 PixelMap
  }

  // 缩放:参数是目标像素尺寸(不是比例!)
  static async scaleTo(pixelMap: image.PixelMap,
    width: number, height: number): Promise<void> {
    await pixelMap.scale(width, height);
  }

  // 旋转:顺时针角度(90 的倍数最常用)
  static async rotate(pixelMap: image.PixelMap, degree: number): Promise<void> {
    await pixelMap.rotate(degree);
  }

  // 编码保存到沙箱目录,返回文件路径
  static async saveJpeg(pixelMap: image.PixelMap,
    quality: number): Promise<string> {
    const packer: image.ImagePacker = image.createImagePacker();
    const packOpts: image.PackingOptions = {
      format: 'image/jpeg', quality: quality };   // quality 仅对 JPEG 生效
    const data: ArrayBuffer = await packer.packing(pixelMap, packOpts);
    const path: string = `${getContext().cacheDir}/edited_${Date.now()}.jpg`;
    const file = fs.openSync(path,
      fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE);
    fs.writeSync(file.fd, data);
    fs.closeSync(file);
    return path;
  }
}

2. 演示页面 entry/src/main/ets/pages/Index.ets(完整代码,选图 → 裁剪 → 保存全链路):

import { picker } from '@kit.CoreFileKit';
import { image } from '@kit.ImageKit';
import { ImageEditor } from '../image/ImageEditor';

@Entry
@Component
struct Index {
  @State showMap: image.PixelMap | undefined = undefined;
  @State savedPath: string = '';
  private origin: image.PixelMap | undefined = undefined;

  build() {
    Column({ space: 14 }) {
      Image(this.showMap)
        .width(280).height(280).objectFit(ImageFit.Contain)
      Button('选择图片').onClick(async () => {
        const photoPicker = new picker.PhotoViewPicker();
        const result = await photoPicker.select({
          MIMEType: picker.PhotoType.IMAGE, maxSelectNumber: 1 });
        if (result.uris.length === 0) { return; }
        this.origin = await ImageEditor.loadEditable(result.uris[0]);
        this.showMap = this.origin;
        this.savedPath = '';
      })
      Button('裁剪左上 1/2').onClick(async () => {
        if (!this.origin) { return; }
        const info = await this.origin.getImageInfo();
        // 副本保护原图:crop 是就地修改
        this.showMap = this.origin.copyPixelMap();
        await ImageEditor.crop(this.showMap, 0, 0,
          Math.floor(info.size.width / 2),
          Math.floor(info.size.height / 2));
        this.savedPath = '';
      })
      Button('缩放到 50%').onClick(async () => {
        if (!this.showMap) { return; }
        const info = await this.showMap.getImageInfo();
        await ImageEditor.scaleTo(this.showMap,
          Math.floor(info.size.width / 2),
          Math.floor(info.size.height / 2));
      })
      Button('顺时针旋转 90 度').onClick(async () => {
        if (!this.showMap) { return; }
        await ImageEditor.rotate(this.showMap, 90);
      })
      Button('压缩保存 JPEG(80)').onClick(async () => {
        if (!this.showMap) { return; }
        this.savedPath = await ImageEditor.saveJpeg(this.showMap, 80);
      })
      Text(this.savedPath ? `已保存:${this.savedPath}` : ' ')
        .fontSize(12).maxLines(1)
    }
    .width('100%').height('100%').padding(16)
  }
}
四、应用场景示例

社交应用"发图前压缩"的标准链路:PhotoViewPicker 选图 → createImageSource + desiredSize 降采样解码(宽高不超过 1080)→ ImagePacker.packing(quality 80)→ 得到小体积 ArrayBuffer 上传服务器。头像裁剪则是:editable 解码 → copyPixelMap 保护原图 → crop 框选区域 → saveJpeg 落盘沙箱 → 上传后 release 释放。

五、技术要点
  1. editable 决定能否编辑:createPixelMap 默认 editable=false,此时 crop/scale/rotate 会失败;需要编辑时显式传 DecodingOptions{ editable: true };
  2. scale 参数是像素不是比例:scale(0.5, 0.5) 是缩到 0.5 像素而不是 50%;正确做法是先 getImageInfo 拿原始宽高,乘系数后取整传入;
  3. crop 就地修改:crop 直接改原 PixelMap 数据,后续还需要原图时先 copyPixelMap() 出副本;Region 坐标越界会失败,需先做边界检查;
  4. 大图降采样:解码时用 DecodingOptions.desiredSize 直接输出小尺寸 PixelMap,比先解大图再 scale 省数倍内存;PixelMap 不用时及时 release();
  5. quality 只对 JPEG 生效:format 支持 image/jpeg、image/png、image/webp、image/heic 等,png 无损不吃 quality;packToFile 可直接写入文件描述符省一次内存拷贝;
  6. picker 与权限:用 PhotoViewPicker 选图无需读写媒体库权限,picker 返回的 uri 自带临时访问授权;从媒体库直接拿路径才需要额外权限。
六、扩展建议

滤镜/色彩类需求走 PixelMap 的 opacity、convertPixelFormat(格式转换)与 readPixels/writePixels 像素级读写;HDR 图片用 Image Kit 的 HDR 处理接口;批量图片处理场景注意串行处理并逐个 release,控制内存峰值;需要用户交互式裁剪框时,UI 层用 Canvas/手势实现选框,把换算后的像素坐标交给 Image Kit 的 crop 执行真正的像素裁剪。

结语

本文用约 130 行 ArkTS 打通了 Image Kit 从选图解码、像素编辑到压缩落盘的完整闭环,核心是"editable 解码、crop 就地修改、scale 传像素、quality 只认 JPEG"四条规则。UI 属性变换与像素数据处理的边界分清后,头像裁剪、图片压缩这类需求就能一次做对。

代码仓库

本文完整示例工程已在 AtomGit 开源,为标准鸿蒙 Stage 工程(AppScope 应用配置、entry 模块、ImageEditor 封装与演示页面、hvigor 构建脚本齐全),DevEco Studio 可直接打开编译运行:https://atomgit.com/NJPJI_Yang/hm-article-2026-12-04-image-kit-image-kit-atomgit

Logo

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

更多推荐