👋 你好,欢迎来到我的博客!我是【菜鸟学鸿蒙】
   我是一名在路上的移动端开发者,正从传统“小码农”转向鸿蒙原生开发的进阶之旅。为了把学习过的知识沉淀下来,也为了和更多同路人互相启发,我决定把探索 HarmonyOS 的过程都记录在这里。
  
  🛠️ 主要方向:ArkTS 语言基础、HarmonyOS 原生应用(Stage 模型、UIAbility/ServiceAbility)、分布式能力与软总线、元服务/卡片、应用签名与上架、性能与内存优化、项目实战,以及 Android → 鸿蒙的迁移踩坑与复盘。
  🧭 内容节奏:从基础到实战——小示例拆解框架认知、专项优化手记、实战项目拆包、面试题思考与复盘,让每篇都有可落地的代码与方法论。
  💡 我相信:写作是把知识内化的过程,分享是让生态更繁荣的方式。
  
   如果你也想拥抱鸿蒙、热爱成长,欢迎关注我,一起交流进步!🚀

前言

图片超分接口本身并不复杂,真正落到应用里时,问题往往出现在接口之外:图片从哪里来,怎样变成 PixelMap,处理过程中如何管理状态,超分结果怎样重新编码,以及怎样让用户明确确认后保存到系统相册。

这次把场景收敛成一个完整的小工具:用户从系统图库选择一张图片,应用读取并展示原图;点击“开始增强”后,通过 HarmonyOS 7 的 Core Vision Kit 执行图像超分;处理完成后展示结果,并允许用户把增强后的图片保存到媒体库。

整个链路可以概括为:

PhotoViewPicker
      ↓
图片 URI
      ↓
fileIo.open()
      ↓
ImageSource
      ↓
PixelMap
      ↓
ImageSRAnalyzer.process()
      ↓
增强后的 PixelMap
      ↓
ImagePacker.packToFile()
      ↓
应用沙箱 JPEG
      ↓
showAssetsCreationDialog()
      ↓
系统媒体库

相比只展示一次 process() 调用,这条链路更接近一个真正可以继续扩展的图片工具。

一、先把 HarmonyOS 7 图像超分的边界弄清楚

本文讨论的是 HarmonyOS 7 中 Core Vision Kit 提供的 imageSuperResolution 图像超分能力。

HarmonyOS 7 对应 API 26。官方 API Reference 标明,imageSuperResolution 从 26.0.0 开始提供。

几个与本文直接相关的条件可以先整理出来:

项目官方约束
系统版本背景HarmonyOS 7
APIAPI 26 / 26.0.0
KitCore Vision Kit
模块imageSuperResolution
核心类ImageSRAnalyzer
系统能力SystemCapability.AI.Vision.VisionBase
应用模型仅支持 Stage 模型
支持设备Phone、Tablet、PC/2in1
地区限制中国境内,不包含香港特别行政区、澳门特别行政区、中国台湾
输入数量单次只支持一张图片
输入尺寸16px < width < 2048px,16px < height < 2048px
官方建议建议处理 1024×1024 以下图片,高分辨率图片可能出现处理超时
输出ISPResponse.pixelMap
输出尺寸官方接口说明为像素同步放大 4 倍
模拟器Core Vision Kit 当前不支持模拟器

这里有两个特别容易理解错的地方。

一个是“4 倍”。

它不是简单把 ArkUI Image 组件的显示宽高放大,而是超分处理结果 ISPResponse.pixelMap 的像素尺寸发生变化。也就是说,真正变化的是图像数据,而不是 UI 的显示比例。

另一个是图片尺寸限制。

如果用户从相册随便选一张照片,完全可能超过超分接口规定的输入范围。因此真正做产品时,不能假定“图库里的图片都可以直接丢给 process()”。至少需要在处理前读取 PixelMap 的尺寸并进行校验。

本文为了把核心链路讲清楚,对超过接口限制的图片直接提示用户重新选择,而不额外引入缩放策略。

二、三个 Kit 各自负责什么

这个工具并不是一个 Kit 就能完成。

Core Vision Kit:负责超分

核心导入为:

import { imageSuperResolution, visionBase } from '@kit.CoreVisionKit';

主要使用三个概念:

ImageSRAnalyzer
visionBase.Request
ISPResponse

基本调用关系是:

const imageData: visionBase.ImageData = {
  pixelMap: inputImage
};

const request: visionBase.Request = {
  inputData: imageData
};

const response: imageSuperResolution.ISPResponse =
  await analyzer.process(request);

const result = response.pixelMap;

Image Kit:负责图片解码和编码

PhotoPicker 返回的是 URI,而超分需要的是 PixelMap。

所以中间需要 Image Kit:

import { image } from '@kit.ImageKit';

选图阶段:

URI → ImageSource → PixelMap

保存阶段则反过来:

PixelMap → ImagePacker → JPEG 文件

Media Library Kit:负责选图和保存

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

本文使用:

photoAccessHelper.PhotoViewPicker

拉起系统图库。

结果保存则使用:

PhotoAccessHelper.showAssetsCreationDialog()

让用户确认是否把应用沙箱中的结果图片保存到媒体库。

这比直接围绕 WRITE_IMAGEVIDEO 权限设计 Demo 更适合普通图片工具:官方文档明确提供了安全控件和授权弹窗两类无长期写权限保存方式。本文选择授权弹窗,因为它更容易把“生成结果 → 用户确认 → 保存相册”的完整过程表达清楚。

三、先搭出工具的状态模型

完整工具和 API Demo 最大的区别之一,就是不能只考虑“调用成功”。

页面至少存在这些状态:

等待选择
   ↓
已选择原图
   ↓
处理中
   ↓
处理完成
   ↓
保存中
   ↓
保存完成

还可能在任意异步步骤进入错误状态。

因此页面需要保存:

@State inputImage: PixelMap | undefined = undefined;
@State outputImage: PixelMap | undefined = undefined;

@State statusText: string = '请选择一张图片';
@State isProcessing: boolean = false;
@State isSaving: boolean = false;

另外还需要管理超分分析器:

private analyzer: imageSuperResolution.ImageSRAnalyzer | null = null;

官方图像超分开发指南给出的生命周期方式很明确:在 aboutToAppear() 创建分析器,在 aboutToDisappear() 中调用 destroy() 释放。

async aboutToAppear(): Promise<void> {
  try {
    this.analyzer =
      await imageSuperResolution.ImageSRAnalyzer.create();
    this.statusText = '图像增强服务已就绪';
  } catch (error) {
    const err = error as BusinessError;
    this.statusText = `初始化失败:${err.message}`;
  }
}

async aboutToDisappear(): Promise<void> {
  if (this.analyzer) {
    await this.analyzer.destroy();
    this.analyzer = null;
  }

  this.releasePixelMaps();
}

这里真正需要关注的不是 create() 本身,而是分析器有明确的资源生命周期。

不要每点一次“增强”就创建一个新实例,又把旧实例留在那里;也不要页面退出后仍然持有不再使用的分析器。

四、第一步:使用 PhotoViewPicker 选择图片

系统图库选择器已经能够完成图片授权和选择交互,没有必要自己做一个相册浏览页面。

选择单张图片:

private async pickImage(): Promise<void> {
  try {
    const options = new photoAccessHelper.PhotoSelectOptions();
    options.MIMEType =
      photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
    options.maxSelectNumber = 1;

    const picker = new photoAccessHelper.PhotoViewPicker();
    const result = await picker.select(options);

    const uri = result.photoUris[0];
    if (!uri) {
      this.statusText = '未选择图片';
      return;
    }

    await this.loadPixelMap(uri);
  } catch (error) {
    const err = error as BusinessError;
    this.statusText = `选择图片失败:${err.message}`;
  }
}

这里刻意把:

maxSelectNumber = 1;

设成 1。

原因不是 UI 简化,而是图像超分 process() 本身只接受单张图片。既然底层能力就是单图处理,第一版工具就没有必要在选择层制造“多选后再排队处理”的额外复杂度。

如果后续真的需要批量增强,可以在应用层维护任务队列,逐张调用,而不是把多张图片一起塞进一次 process()。

五、把图库 URI 转换成 PixelMap

拿到 URI 后还不能直接调用超分接口。

官方图像超分开发指南采用的链路是:

fileIo.open(uri)
        ↓
image.createImageSource(fd)
        ↓
imageSource.createPixelMap()

对应代码可以封装成:

private async loadPixelMap(uri: string): Promise<void> {
  let source: image.ImageSource | undefined = undefined;
  let file: fileIo.File | undefined = undefined;

  try {
    file = await fileIo.open(uri, fileIo.OpenMode.READ_ONLY);

    source = image.createImageSource(file.fd);

    const pixelMap = await source.createPixelMap();
    const info = pixelMap.getImageInfoSync();

    const width = info.size.width;
    const height = info.size.height;

    if (width <= 16 || width >= 2048 ||
        height <= 16 || height >= 2048) {
      await pixelMap.release();
      this.statusText =
        `当前图片尺寸为 ${width}×${height},不符合图像超分输入范围`;
      return;
    }

    if (this.inputImage) {
      await this.inputImage.release();
    }

    if (this.outputImage) {
      await this.outputImage.release();
      this.outputImage = undefined;
    }

    this.inputImage = pixelMap;
    this.statusText =
      `已选择图片:${width}×${height}`;
  } finally {
    if (source) {
      await source.release();
    }

    if (file) {
      await fileIo.close(file);
    }
  }
}

这一段有一个很重要的设计点:尺寸检查应该发生在调用 AI 接口之前。

官方明确给出了:

16px < width < 2048px
16px < height < 2048px

所以不需要等 process() 报错之后才知道图片不合适。

实际项目还可以进一步采用官方建议,把 1024×1024 作为一个业务层面的提醒阈值,因为官方指出高分辨率图片可能出现处理超时。

需要区分:

2048 是接口输入边界;
1024 是官方建议处理尺寸。

这两个概念不能混在一起。

六、核心:调用 ImageSRAnalyzer 完成图像超分

准备好 PixelMap 后,真正的超分代码反而非常短。

private async enhanceImage(): Promise<void> {
  if (!this.inputImage) {
    this.statusText = '请先选择图片';
    return;
  }

  if (!this.analyzer) {
    this.statusText = '图像增强服务尚未就绪';
    return;
  }

  if (this.isProcessing) {
    return;
  }

  this.isProcessing = true;
  this.statusText = '正在增强图片...';

  try {
    const imageData: visionBase.ImageData = {
      pixelMap: this.inputImage
    };

    const request: visionBase.Request = {
      inputData: imageData
    };

    const response: imageSuperResolution.ISPResponse =
      await this.analyzer.process(request);

    if (this.outputImage) {
      await this.outputImage.release();
    }

    this.outputImage = response.pixelMap;

    const info = this.outputImage.getImageInfoSync();
    this.statusText =
      `处理完成:${info.size.width}×${info.size.height}`;
  } catch (error) {
    const err = error as BusinessError;
    this.statusText =
      `图像增强失败:${err.code} ${err.message}`;
  } finally {
    this.isProcessing = false;
  }
}

真正需要关注的是三个对象。

visionBase.ImageData

它负责携带输入图像:

const imageData: visionBase.ImageData = {
  pixelMap: this.inputImage
};

visionBase.Request

再把 ImageData 放进请求:

const request: visionBase.Request = {
  inputData: imageData
};

ISPResponse.pixelMap

处理完成后:

const response =
  await this.analyzer.process(request);

this.outputImage = response.pixelMap;

这个 pixelMap 才是真正应该显示和保存的增强结果。

官方 API 对 ISPResponse.pixelMap 的说明是:经过超分后的图片,在提高图像质量的同时,像素同步放大四倍。

因此不要在拿到结果后又机械执行一次:

pixelMap.scale(...)

否则做的已经不是“取得超分结果”,而是在超分结果上继续进行普通缩放。

七、为什么需要阻止连续点击

页面里增加了:

@State isProcessing: boolean = false;

并在入口判断:

if (this.isProcessing) {
  return;
}

这不是单纯为了避免按钮被多点几次。

Core Vision Kit 官方约束中明确指出,同一用户不支持并发调用同一个特性;同一进程在同一时间多次调用同一特性可能返回系统繁忙错误。

所以 UI 状态应该直接体现底层能力边界。

按钮可以写成:

Button(this.isProcessing ? '处理中...' : '开始增强')
  .enabled(!this.isProcessing && this.inputImage !== undefined)
  .onClick(() => {
    void this.enhanceImage();
  })

这样比允许用户连续创建多个处理任务,再依赖异常兜底更合理。

八、把增强结果编码到应用沙箱

到这里已经能够展示结果,但还不能直接把 PixelMap 当作一个 JPEG 文件保存到相册。

需要先编码。

Image Kit 提供 ImagePacker。当前接口中可以使用:

packToFile(
  source: PixelMap,
  fd: number,
  options: PackingOption
): Promise<void>

我们先把结果写到应用沙箱:

private async encodeResultToSandbox(): Promise<string> {
  if (!this.outputImage) {
    throw new Error('没有可保存的增强结果');
  }

  const context = this.getUIContext().getHostContext()
    as common.UIAbilityContext;

  const path =
    `${context.filesDir}/enhanced_result_${Date.now()}.jpg`;

  const file = fileIo.openSync(
    path,
    fileIo.OpenMode.CREATE |
    fileIo.OpenMode.READ_WRITE
  );

  const packer = image.createImagePacker();

  try {
    const options: image.PackingOption = {
      format: 'image/jpeg',
      quality: 95
    };

    await packer.packToFile(
      this.outputImage,
      file.fd,
      options
    );

    return path;
  } finally {
    await packer.release();
    fileIo.closeSync(file);
  }
}

这里选择 JPEG 只是这个 Demo 的输出策略,并不是图像超分要求必须输出 JPEG。

ImagePacker 和图像超分是两个不同层面的能力:

ImageSRAnalyzer
负责生成增强后的 PixelMap

ImagePacker
负责把 PixelMap 编码成 JPEG / PNG 等文件

不要把“超分输出格式”和“保存文件格式”混成一件事。

还有一个资源管理细节需要单独强调。

官方 ImagePacker 文档提醒,在编码过程中不要提前修改或释放作为输入的 PixelMap。所以正确顺序应该是:

packToFile()
    ↓
等待 Promise 完成
    ↓
关闭文件
    ↓
后续再决定什么时候释放 PixelMap

而不是刚调用 packToFile() 就执行 outputImage.release()。

九、通过授权弹窗保存到系统相册

普通图片工具通常没有必要因为一个“保存结果”按钮长期申请媒体库写权限。

Media Library Kit 提供:

showAssetsCreationDialog()

用于让用户确认保存。

先把沙箱路径转换成 URI:

const srcUri = fileUri.getUriFromPath(path);

然后准备图片创建配置:

const config: photoAccessHelper.PhotoCreationConfig = {
  title: `enhanced_${Date.now()}`,
  fileNameExtension: 'jpg',
  photoType: photoAccessHelper.PhotoType.IMAGE
};

获取 PhotoAccessHelper:

const context = this.getUIContext().getHostContext()
  as common.UIAbilityContext;

const helper =
  photoAccessHelper.getPhotoAccessHelper(context);

拉起保存确认弹窗:

const targetUris =
  await helper.showAssetsCreationDialog(
    [srcUri],
    [config]
  );

如果用户拒绝:

if (targetUris.length === 0) {
  this.statusText = '已取消保存';
  return;
}

用户同意后,接口返回已经创建并授予应用写入权限的媒体库 URI。

接下来把沙箱中的 JPEG 内容复制过去:

const srcFile =
  fileIo.openSync(srcUri, fileIo.OpenMode.READ_ONLY);

const destFile =
  fileIo.openSync(
    targetUris[0],
    fileIo.OpenMode.READ_WRITE |
    fileIo.OpenMode.CREATE
  );

try {
  fileIo.copyFileSync(srcFile.fd, destFile.fd);
} finally {
  fileIo.closeSync(srcFile);
  fileIo.closeSync(destFile);
}

组合成完整方法:

private async saveResult(): Promise<void> {
  if (!this.outputImage || this.isSaving) {
    return;
  }

  this.isSaving = true;
  this.statusText = '正在准备保存...';

  try {
    const path = await this.encodeResultToSandbox();
    const srcUri = fileUri.getUriFromPath(path);

    const context = this.getUIContext().getHostContext()
      as common.UIAbilityContext;

    const helper =
      photoAccessHelper.getPhotoAccessHelper(context);

    const config: photoAccessHelper.PhotoCreationConfig = {
      title: `enhanced_${Date.now()}`,
      fileNameExtension: 'jpg',
      photoType: photoAccessHelper.PhotoType.IMAGE
    };

    const targetUris =
      await helper.showAssetsCreationDialog(
        [srcUri],
        [config]
      );

    if (targetUris.length === 0) {
      this.statusText = '已取消保存';
      return;
    }

    const srcFile =
      fileIo.openSync(srcUri, fileIo.OpenMode.READ_ONLY);

    const destFile =
      fileIo.openSync(
        targetUris[0],
        fileIo.OpenMode.READ_WRITE |
        fileIo.OpenMode.CREATE
      );

    try {
      fileIo.copyFileSync(srcFile.fd, destFile.fd);
    } finally {
      fileIo.closeSync(srcFile);
      fileIo.closeSync(destFile);
    }

    this.statusText = '增强结果已保存';
  } catch (error) {
    const err = error as BusinessError;
    this.statusText =
      `保存失败:${err.code ?? ''} ${err.message}`;
  } finally {
    this.isSaving = false;
  }
}

这里还有一个容易忽略的配置要求。

官方 showAssetsCreationDialog() 文档明确要求应用确保 module.json5 中 Ability 配置了 label 和 icon。

例如:

{
  "module": {
    "abilities": [
      {
        "name": "EntryAbility",
        "srcEntry": "./ets/entryability/EntryAbility.ets",
        "description": "$string:EntryAbility_desc",
        "icon": "$media:layered_image",
        "label": "$string:EntryAbility_label",
        "startWindowIcon": "$media:startIcon",
        "startWindowBackground": "$color:start_window_background",
        "exported": true
      }
    ]
  }
}

这里只展示与本文有关的 Ability 配置位置,实际工程仍应以 DevEco Studio 创建项目时生成的配置为基础,不建议为了照抄 Demo 覆盖整个 module.json5。

十、把这些能力组合成一个页面

把前面的功能拼起来以后,页面本身不需要复杂。

下面代码重点展示交互组织方式:

import { imageSuperResolution, visionBase } from '@kit.CoreVisionKit';
import { image } from '@kit.ImageKit';
import { photoAccessHelper } from '@kit.MediaLibraryKit';
import { fileIo, fileUri } from '@kit.CoreFileKit';
import { common } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

@Entry
@Component
struct Index {
  @State inputImage: PixelMap | undefined = undefined;
  @State outputImage: PixelMap | undefined = undefined;

  @State statusText: string = '请选择一张图片';
  @State isProcessing: boolean = false;
  @State isSaving: boolean = false;

  private analyzer:
    imageSuperResolution.ImageSRAnalyzer | null = null;

  async aboutToAppear(): Promise<void> {
    try {
      this.analyzer =
        await imageSuperResolution.ImageSRAnalyzer.create();

      this.statusText = '图像增强服务已就绪';
    } catch (error) {
      const err = error as BusinessError;
      this.statusText =
        `初始化图像增强服务失败:${err.message}`;
    }
  }

  async aboutToDisappear(): Promise<void> {
    if (this.analyzer) {
      await this.analyzer.destroy();
      this.analyzer = null;
    }

    await this.releasePixelMaps();
  }

  private async releasePixelMaps(): Promise<void> {
    if (this.inputImage) {
      await this.inputImage.release();
      this.inputImage = undefined;
    }

    if (this.outputImage) {
      await this.outputImage.release();
      this.outputImage = undefined;
    }
  }

  private async pickImage(): Promise<void> {
    try {
      const options =
        new photoAccessHelper.PhotoSelectOptions();

      options.MIMEType =
        photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
      options.maxSelectNumber = 1;

      const picker =
        new photoAccessHelper.PhotoViewPicker();

      const result = await picker.select(options);
      const uri = result.photoUris[0];

      if (!uri) {
        this.statusText = '未选择图片';
        return;
      }

      await this.loadPixelMap(uri);
    } catch (error) {
      const err = error as BusinessError;
      this.statusText =
        `选择图片失败:${err.message}`;
    }
  }

  private async loadPixelMap(uri: string): Promise<void> {
    let source: image.ImageSource | undefined = undefined;
    let file: fileIo.File | undefined = undefined;

    try {
      file =
        await fileIo.open(uri, fileIo.OpenMode.READ_ONLY);

      source = image.createImageSource(file.fd);

      const pixelMap =
        await source.createPixelMap();

      const info = pixelMap.getImageInfoSync();
      const width = info.size.width;
      const height = info.size.height;

      if (width <= 16 || width >= 2048 ||
          height <= 16 || height >= 2048) {
        await pixelMap.release();

        this.statusText =
          `图片 ${width}×${height} 不符合超分输入范围`;
        return;
      }

      if (this.inputImage) {
        await this.inputImage.release();
      }

      if (this.outputImage) {
        await this.outputImage.release();
        this.outputImage = undefined;
      }

      this.inputImage = pixelMap;
      this.statusText =
        `原图尺寸:${width}×${height}`;
    } finally {
      if (source) {
        await source.release();
      }

      if (file) {
        await fileIo.close(file);
      }
    }
  }

  private async enhanceImage(): Promise<void> {
    if (!this.inputImage) {
      this.statusText = '请先选择图片';
      return;
    }

    if (!this.analyzer) {
      this.statusText = '图像增强服务尚未就绪';
      return;
    }

    if (this.isProcessing) {
      return;
    }

    this.isProcessing = true;
    this.statusText = '正在增强图片...';

    try {
      const imageData: visionBase.ImageData = {
        pixelMap: this.inputImage
      };

      const request: visionBase.Request = {
        inputData: imageData
      };

      const response:
        imageSuperResolution.ISPResponse =
        await this.analyzer.process(request);

      if (this.outputImage) {
        await this.outputImage.release();
      }

      this.outputImage = response.pixelMap;

      const info =
        this.outputImage.getImageInfoSync();

      this.statusText =
        `增强完成:${info.size.width}×${info.size.height}`;
    } catch (error) {
      const err = error as BusinessError;

      this.statusText =
        `增强失败:${err.code} ${err.message}`;
    } finally {
      this.isProcessing = false;
    }
  }

  private async encodeResultToSandbox(): Promise<string> {
    if (!this.outputImage) {
      throw new Error('没有可保存的图片');
    }

    const context =
      this.getUIContext().getHostContext()
        as common.UIAbilityContext;

    const path =
      `${context.filesDir}/enhanced_result_${Date.now()}.jpg`;

    const file = fileIo.openSync(
      path,
      fileIo.OpenMode.CREATE |
      fileIo.OpenMode.READ_WRITE
    );

    const packer = image.createImagePacker();

    try {
      const options: image.PackingOption = {
        format: 'image/jpeg',
        quality: 95
      };

      await packer.packToFile(
        this.outputImage,
        file.fd,
        options
      );

      return path;
    } finally {
      await packer.release();
      fileIo.closeSync(file);
    }
  }

  private async saveResult(): Promise<void> {
    if (!this.outputImage || this.isSaving) {
      return;
    }

    this.isSaving = true;
    this.statusText = '正在准备保存...';

    try {
      const path =
        await this.encodeResultToSandbox();

      const srcUri =
        fileUri.getUriFromPath(path);

      const context =
        this.getUIContext().getHostContext()
          as common.UIAbilityContext;

      const helper =
        photoAccessHelper.getPhotoAccessHelper(context);

      const config:
        photoAccessHelper.PhotoCreationConfig = {
          title: `enhanced_${Date.now()}`,
          fileNameExtension: 'jpg',
          photoType: photoAccessHelper.PhotoType.IMAGE
        };

      const targetUris =
        await helper.showAssetsCreationDialog(
          [srcUri],
          [config]
        );

      if (targetUris.length === 0) {
        this.statusText = '已取消保存';
        return;
      }

      const srcFile =
        fileIo.openSync(
          srcUri,
          fileIo.OpenMode.READ_ONLY
        );

      const destFile =
        fileIo.openSync(
          targetUris[0],
          fileIo.OpenMode.READ_WRITE |
          fileIo.OpenMode.CREATE
        );

      try {
        fileIo.copyFileSync(
          srcFile.fd,
          destFile.fd
        );
      } finally {
        fileIo.closeSync(srcFile);
        fileIo.closeSync(destFile);
      }

      this.statusText = '增强结果已保存';
    } catch (error) {
      const err = error as BusinessError;

      this.statusText =
        `保存失败:${err.code ?? ''} ${err.message}`;
    } finally {
      this.isSaving = false;
    }
  }

  build() {
    Column({ space: 12 }) {
      Text('图片增强工具')
        .fontSize(26)
        .fontWeight(FontWeight.Bold)
        .width('100%')

      Text(this.statusText)
        .fontSize(14)
        .fontColor('#666666')
        .width('100%')

      Row({ space: 12 }) {
        Column({ space: 8 }) {
          Text('原图')
            .fontSize(16)
            .fontWeight(FontWeight.Medium)

          Image(this.inputImage)
            .width('100%')
            .height(240)
            .objectFit(ImageFit.Contain)
            .backgroundColor('#F5F5F5')
        }
        .layoutWeight(1)

        Column({ space: 8 }) {
          Text('增强结果')
            .fontSize(16)
            .fontWeight(FontWeight.Medium)

          Image(this.outputImage)
            .width('100%')
            .height(240)
            .objectFit(ImageFit.Contain)
            .backgroundColor('#F5F5F5')
        }
        .layoutWeight(1)
      }
      .width('100%')

      Button('选择图片')
        .width('100%')
        .onClick(() => {
          void this.pickImage();
        })

      Button(
        this.isProcessing ?
        '处理中...' :
        '开始增强'
      )
        .width('100%')
        .enabled(
          this.inputImage !== undefined &&
          !this.isProcessing
        )
        .onClick(() => {
          void this.enhanceImage();
        })

      Button(
        this.isSaving ?
        '保存中...' :
        '保存增强结果'
      )
        .width('100%')
        .enabled(
          this.outputImage !== undefined &&
          !this.isSaving
        )
        .onClick(() => {
          void this.saveResult();
        })
    }
    .padding(20)
    .width('100%')
    .height('100%')
  }
}

这段代码按照官方接口定义把完整链路组织在一个页面里,重点是展示各能力之间怎样衔接。由于本文没有在具体 DevEco Studio 工程和目标真机上实际执行编译、签名和运行,因此不能把它描述为已经完成真机验证;实际使用时仍应以当前 HarmonyOS 7 SDK、目标设备以及 DevEco Studio 编译结果继续校验。

十一、几个关键点拆开看

1. PhotoPicker 和读取整个媒体库不是一回事

这个工具的需求只是“让用户明确选择一张图片”。

这种情况下直接使用 PhotoViewPicker 更符合需求,没有必要为了选一张图片先设计成遍历整个媒体库。

开发时应该先问:

我的业务需要访问整个媒体库,还是只需要用户选择的文件?

两者的权限设计和业务边界并不相同。

本文使用的是后一种。

2. 超分不是普通 resize

普通缩放改变的是像素排列和输出尺寸。

Core Vision Kit 的图像超分属于 AI 图像处理能力,官方描述包含纹理细节补全、边缘优化和噪点降低等处理。

因此:

ImageSRAnalyzer.process()

和:

PixelMap.scale()

不是同一种能力。

如果需求只是生成一个尺寸更大的缩略图,没有必要为了“变大”而调用 AI 超分。

3. 处理结果不要只停留在 Image 组件里

很多最小 Demo 做到:

this.outputImage = response.pixelMap;

然后:

Image(this.outputImage)

就结束了。

但工具类应用真正需要解决的是结果流转:

PixelMap
→ 编码
→ 文件
→ 用户授权
→ 媒体库

把这一段补上以后,图像超分才从“接口演示”变成一个能够继续扩展的业务能力。

4. 生命周期和图像资源都需要主动释放

本文至少涉及:

ImageSRAnalyzer
ImageSource
ImagePacker
PixelMap
File

这些对象并不适合无限持有。

官方文档对于 ImageSource、ImagePacker、PixelMap 和 ImageSRAnalyzer 都提供了相应的资源释放方式。

尤其需要避免这种写法:

packer.packToFile(pixelMap, fd, options);
pixelMap.release();

因为编码操作还没有完成。

应该:

await packer.packToFile(pixelMap, fd, options);
// 完成后再进入后续释放逻辑

异步图片处理代码里,“什么时候释放”往往比“有没有调用 release”更容易出问题。

5. 不要在模拟器上判断超分能力是否正常

Core Vision Kit 官方当前明确标注不支持模拟器。

所以如果:

ImageSRAnalyzer.create()

在模拟器环境没有得到预期结果,排查顺序里应该先确认运行环境,而不是马上怀疑 Request 构造或者 PixelMap 解码代码。

对于本文场景,最终验证环境应当是满足 Core Vision Kit 支持条件的目标设备。

十二、容易出现的几个理解偏差

把 API 26 写成旧版本也可以使用

不可以。

imageSuperResolution 的起始版本明确是 26.0.0。

如果项目的编译环境还没有对应 API,就不能因为其他图片 API 很早就存在,而认为图像超分也存在。

把 2048×2048 理解成推荐尺寸

也不准确。

官方给出的能力限制是:

16px < width < 2048px
16px < height < 2048px

同时又给出了建议:

建议处理 1024px × 1024px 以下图片

后者与高分辨率图片可能出现处理超时有关。

所以一个完整工具至少应该区分“合法”和“推荐”两个概念。

连续点击按钮同时发起多个 process

Core Vision Kit 对同一用户并发调用同一特性存在明确限制。

因此按钮状态不是可有可无的 UI 装饰。

.enabled(!this.isProcessing)

实际上是在把底层能力约束映射到交互层。

保存结果就一定要申请 WRITE_IMAGEVIDEO

不能这么理解。

Media Library Kit 官方提供了不依赖长期媒体库写权限的用户授权保存方式,包括安全控件以及保存确认弹窗。

对于本文这种“用户点击保存单张处理结果”的场景,使用系统授权交互会更自然。

是否需要申请媒体库相关权限,应该根据真实业务场景和官方权限使用规范判断,而不是看到“保存图片”四个字就直接往 module.json5 添加权限。

十三、实际项目中可以按什么顺序排查

当图像增强工具没有达到预期时,可以按下面的顺序检查。

排查顺序检查内容
1当前工程是否使用 HarmonyOS 7 / API 26 对应 SDK
2是否为 Stage 模型
3是否运行在 Core Vision Kit 支持的设备和地区
4是否误用模拟器验证 Core Vision Kit
5PhotoViewPicker 是否真正返回了图片 URI
6URI 是否能够通过 fileIo.open() 打开
7是否成功创建 ImageSource 和 PixelMap
8PixelMap 宽高是否满足 16 < size < 2048
9是否已经成功创建 ImageSRAnalyzer
10是否存在同一特性的并发处理
11Request.inputData 是否正确携带 PixelMap
12response.pixelMap 是否仍然有效
13保存前是否成功通过 ImagePacker 生成沙箱文件
14showAssetsCreationDialog() 的 URI 是否由真实沙箱路径转换得到
15用户确认后是否真正把源文件内容写入返回的媒体库 URI
16是否过早释放 PixelMap、ImageSource、ImagePacker 或关闭文件

这种排查方式的好处是把问题拆成:

环境
↓
选图
↓
解码
↓
输入校验
↓
AI 处理
↓
编码
↓
媒体库保存

哪一层断了,就先查哪一层。

如果一开始就把所有异常都归结为“超分接口调用失败”,反而很难定位。

十四、从 Demo 继续往真正工具扩展

完成本文的最小链路之后,可以继续扩展,但建议仍然围绕现有边界来设计。

例如增加原图与结果图切换:

原图 / 增强结果

或者做拖动对比。

也可以在选择图片后读取尺寸:

800 × 600

增强完成后再展示:

3200 × 2400

这样用户能够直观看到图像数据发生了变化。

如果希望支持超出输入规格的大图,则应该增加一个明确的预处理阶段:

用户原图
   ↓
检查尺寸
   ↓
按业务规则缩放 / 裁剪
   ↓
生成符合要求的 PixelMap
   ↓
图像超分

这里不要偷偷修改用户原图。

更合理的方式是把“原始图片”和“送入超分模型的输入图片”视为两个不同对象。

批量增强也是同样的思路。PhotoPicker 可以扩展为多选,但 Core Vision Kit 的单次超分仍然按照单图处理,因此应用层需要做串行任务管理,而不是把底层接口想象成批处理 API。

开发经验总结

把 HarmonyOS 7 图像超分做成一个真正能交互的小工具后,可以看到这项能力本身只占整条链路的一部分。

真正值得迁移到实际项目里的有五点。

第一,imageSuperResolution 是 HarmonyOS 7 / API 26 新增能力,接入之前先检查版本、Stage 模型、设备和地区条件,不能只确认 import 是否存在。

第二,超分接口消费的是 PixelMap。来自图库的 URI 需要经过文件访问和 Image Kit 解码,输出结果如果要保存,也需要重新通过 ImagePacker 编码。

第三,输入尺寸应该在 process() 前主动检查。官方限制宽高分别处于 16px 到 2048px 之间,并建议优先处理 1024×1024 以下图片。

第四,ImageSRAnalyzer 有明确的创建、处理和销毁生命周期,同时同一特性不适合并发调用,因此页面的 loading 状态实际上也是能力约束的一部分。

第五,结果保存最好单独设计成一个用户动作。对于“保存一张处理后的图片”这种场景,可以使用 Media Library Kit 提供的系统授权保存流程,不应该为了省几行代码就默认申请长期媒体库写权限。

从应用结构来看,这个工具最终可以拆成四层:

Picker
负责用户选图

Image Decoder / Encoder
负责 PixelMap 与文件之间转换

Image Super Resolution
负责图像增强

Media Library
负责最终结果保存

这样组织之后,后面无论增加图片裁剪、尺寸预处理、结果对比、任务队列还是缓存,都不需要重新修改超分能力本身。

图像超分真正值得关注的也正是这里:process() 只有很短的一段代码,但一个能够让用户选择、处理、查看并保存结果的图片工具,需要把媒体访问、图片编解码、AI 能力生命周期和系统授权流程完整串起来。

📝 写在最后

如果你觉得这篇文章对你有帮助,或者有任何想法、建议,欢迎在评论区留言交流!你的每一个点赞 👍、收藏 ⭐、关注 ❤️,都是我持续更新的最大动力!

我是一个在代码世界里不断摸索的小码农,愿我们都能在成长的路上越走越远,越学越强!

感谢你的阅读,我们下篇文章再见~👋

✍️ 作者:菜鸟不学编程
🧵 本文原创,转载请注明出处。

Logo

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

更多推荐