一、背景说明

HarmonyOS 26.0.1 开发者套件发布后,应用侧对公共媒体库(图库)的读写需求越来越常见:编辑器导出图片、拍摄作品存档、批量导出海报等。本文聚焦一个具体技术点:使用 Media Library Kit 的 photoAccessHelper 模块,在不申请 ohos.permission.WRITE_IMAGEVIDEO 权限的前提下,通过安全控件(SaveButton)与授权弹窗两种方式把应用沙箱中的图片保存到系统图库,并完成资产变更监听与查询(本文源码已在 AtomGit 仓库开源,见文末)。

二、技术原理

Media Library Kit(媒体文件管理服务)提供图片、视频资产的公共媒体库管理能力,核心概念:

  • PhotoAccessHelper(相册管理实例):通过 photoAccessHelper.getPhotoAccessHelper(context) 获取,是所有媒体库操作的入口。
  • 安全控件保存(SaveButton):SaveButton 是系统级安全控件,用户点击瞬间系统临时授权,应用可直接调用 applyChanges 创建资产,全程无需权限申请。
  • 弹窗授权保存(showAssetsCreationDialog):一次弹窗最多保存 100 张图片,用户确认后返回已授权的目标 URI 列表,应用用 fileIo 把沙箱内容写入即可。
  • 变更监听(registerChange):注册对 DEFAULT_PHOTO_URI 的监听,资产保存成功后收到 NOTIFY_ADD 通知,可用于保存后立即读取资产 URI。
  • 格式查询(getSupportedPhotoFormats):保存前可查询系统支持的图片/视频格式(jpg、png、mp4 等)。

数据流:getPhotoAccessHelper(入口) → 沙箱准备图片 → SaveButton/showAssetsCreationDialog(临时授权) → applyChanges 或写入目标 URI → registerChange(监听 NOTIFY_ADD) → getAssets(查询确认)。

三、实现步骤

工程为 Stage 模型(API 12+)。先在 entry/src/main/resources/rawfile/ 放一张 test.jpg,启动时拷贝到沙箱 filesDir 作为待保存素材。

1. 媒体库管理类 MediaGallery.ets
import { photoAccessHelper } from '@kit.MediaLibraryKit';
import { fileIo as fs } from '@kit.CoreFileKit';
import { common } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

export class MediaGallery {
  private context: common.UIAbilityContext;

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

  private helper(): photoAccessHelper.PhotoAccessHelper {
    return photoAccessHelper.getPhotoAccessHelper(this.context);
  }

  // 第一步:把 rawfile 中的测试图片拷贝到沙箱 filesDir
  async prepareSandboxImage(fileName: string): Promise<string> {
    const rawFile = await this.context.resourceManager.getRawFd(fileName);
    const src = fs.readSync(rawFile.fd); // 只读元信息即可,直接按 fd 拷贝
    const dstPath = this.context.filesDir + '/test.jpg';
    const dst = fs.openSync(dstPath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
    fs.writeSync(dst.fd, src.buffer);
    fs.closeSync(dst);
    return dstPath;
  }

  // 第二步:查询系统支持的保存格式
  async listSupportedFormats(): Promise<string> {
    const imageFormats = await this.helper().getSupportedPhotoFormats(
      photoAccessHelper.PhotoType.IMAGE);
    return imageFormats.join(', ');
  }

  // 第三步:安全控件保存——createImageAssetRequest + applyChanges
  async saveBySaveButton(): Promise<string> {
    const phHelper = this.helper();
    // 需要确保 fileUri 对应的资源存在
    const fileUri = 'file://' + this.context.filesDir + '/test.jpg';
    const request: photoAccessHelper.MediaAssetChangeRequest =
      photoAccessHelper.MediaAssetChangeRequest.createImageAssetRequest(this.context, fileUri);
    await phHelper.applyChanges(request);
    return request.getAsset().uri;
  }

  // 第四步:弹窗授权保存——showAssetsCreationDialog + fileIo 写入
  async saveByDialog(): Promise<string> {
    const srcFileUri = this.context.filesDir + '/test.jpg';
    const configs: photoAccessHelper.PhotoCreationConfig[] = [{
      title: 'harmony_' + Date.now(),
      fileNameExtension: 'jpg',
      photoType: photoAccessHelper.PhotoType.IMAGE,
      subtype: photoAccessHelper.PhotoSubtype.DEFAULT
    }];
    const desFileUris: string[] =
      await this.helper().showAssetsCreationDialog([srcFileUri], configs);
    if (desFileUris.length === 0) {
      throw new Error('用户取消了保存授权');
    }
    let srcFile: fs.File | null = null;
    let desFile: fs.File | null = null;
    try {
      desFile = await fs.open(desFileUris[0], fs.OpenMode.WRITE_ONLY);
      srcFile = await fs.open(srcFileUri, fs.OpenMode.READ_ONLY);
      await fs.copyFile(srcFile.fd, desFile.fd);
      return desFileUris[0];
    } finally {
      if (srcFile) fs.closeSync(srcFile);
      if (desFile) fs.closeSync(desFile);
    }
  }

  // 第五步:按 URI 查询资产确认保存结果
  async queryAsset(uri: string): Promise<photoAccessHelper.PhotoAsset> {
    const predicates = new dataSharePredicates.DataSharePredicates();
    predicates.equalTo(photoAccessHelper.PhotoKeys.URI, uri);
    const fetchOptions: photoAccessHelper.FetchOptions = {
      fetchColumns: [],
      predicates: predicates
    };
    const result = await this.helper().getAssets(fetchOptions);
    return result.getFirstObject();
  }
}

// 文件头部补充导入
import { dataSharePredicates } from '@kit.ArkData';
2. UI 调用示例 Index.ets
import { photoAccessHelper } from '@kit.MediaLibraryKit';
import { common } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { MediaGallery } from '../model/MediaGallery';

@Entry
@Component
struct Index {
  @State message: string = '';
  private gallery: MediaGallery = new MediaGallery(getContext(this) as common.UIAbilityContext);
  saveButtonOptions: SaveButtonOptions = {
    icon: SaveIconStyle.FULL_FILLED,
    text: SaveDescription.SAVE_IMAGE,
    buttonType: ButtonType.Capsule
  };

  build() {
    Column({ space: 16 }) {
      Text('Media Library Kit 媒体库保存').fontSize(18).fontWeight(FontWeight.Bold)

      Button('查询支持格式').onClick(async () => {
        try {
          await this.gallery.prepareSandboxImage('test.jpg');
          this.message = '支持格式:' + await this.gallery.listSupportedFormats();
        } catch (err) {
          this.message = `格式查询失败 code=${(err as BusinessError).code}`;
        }
      })

      // 安全控件:点击瞬间系统临时授权,无需权限申请
      SaveButton(this.saveButtonOptions).onClick(async (event, result: SaveButtonOnClickResult) => {
        if (result == SaveButtonOnClickResult.SUCCESS) {
          try {
            const uri = await this.gallery.saveBySaveButton();
            const asset = await this.gallery.queryAsset(uri);
            this.message = '保存成功:' + asset.displayName;
          } catch (err) {
            this.message = `保存失败 code=${(err as BusinessError).code}`;
          }
        } else {
          this.message = '安全控件授权失败';
        }
      })

      Button('弹窗授权保存').onClick(async () => {
        try {
          const uri = await this.gallery.saveByDialog();
          this.message = '弹窗保存成功:' + uri;
        } catch (err) {
          this.message = `弹窗保存失败 ${(err as BusinessError).message}`;
        }
      })

      Text(this.message).fontSize(14)
    }
    .width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }
}
四、应用场景示例

保存后即时监听资产新增——注册 DEFAULT_PHOTO_URI 监听,收到 NOTIFY_ADD 后执行后续业务(如插入相册封面、同步云端):

const onCallback = (changeData: photoAccessHelper.ChangeData) => {
  for (let i = 0; i < changeData.uris.length; i++) {
    if (changeData.type === photoAccessHelper.NotifyType.NOTIFY_ADD) {
      console.info('新增资产:' + changeData.uris[i]);
    }
  }
};
phAccessHelper.registerChange(
  photoAccessHelper.DefaultChangeUri.DEFAULT_PHOTO_URI, true, onCallback);
// 业务结束后调用 unRegisterChange 注销监听
五、技术要点
1. 两种免权限方式的选择

SaveButton 适合单张、需要用户主动确认的场景,权限在点击瞬间生效;showAssetsCreationDialog 支持一次最多 100 张批量保存,返回的 URI 授权永久生效,适合导出多图的场景。两种方式都不需要 ohos.permission.WRITE_IMAGEVIDEO。

2. 弹窗授权的配置要求

showAssetsCreationDialog 的弹窗需要显示应用名称,依赖 module.json5 中 abilities 标签的 label 与 icon 配置,缺失会导致弹窗异常。传入沙箱路径可正常保存但无预览界面。

3. 错误处理
try {
  await this.gallery.saveByDialog();
} catch (err) {
  const e = err as BusinessError;
  console.error(`media library error code=${e.code}, message=${e.message}`);
}

常见错误:-2004 图片类型与后缀不符、-3006 文件名含非法字符、-203 文件操作异常。

六、扩展建议
  1. 视频保存:将 photoType 换为 PhotoType.VIDEO 即可保存 mp4 视频;音频需改用 AudioViewPicker;
  2. addResource 写入:除 fileUri 外,还支持通过 addResource 接口以 ArrayBuffer 方式添加资源内容;
  3. 相册分组:可配合 createPhotoAlbum 把保存的资产归入自定义相册,便于用户整理。
结语

本文用 Media Library Kit 完成了从沙箱图片到系统图库的免权限保存(安全控件 + 弹窗授权两种路径)、格式查询与资产变更监听,核心代码约 150 行,均已开源到文末 AtomGit 仓库。理解安全控件的临时授权模型后,图库导出类功能即可稳定落地。

代码仓库

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

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

Logo

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

更多推荐