[经验分享] OpenHarmony应用访问相册和图片

深开鸿-孙炼 显示全部楼层 发表于 2023-12-18 11:07:54

简介

使用[@ohos.file.photoAccessHelper](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-photoAccessHelper.md)
接口,可以实现查看系统相册、创建用户相册、查看相册照片、用户相册文件添加和删除、以及预览图片、最近删除、收藏夹操作等功能。

环境

1. 支持标准系统上运行,支持设备:RK3568;
2. 支持API10版本SDK,版本号:4.0.9.1,镜像版本号:OpenHarmony 4.0.9.1,需要手动替换Full SDK才能编译通过,具体操作可参考[替换指南](https://docs.openharmony.cn/pages/v3.2/zh-cn/application-dev/quick-start/full-sdk-switch-guide.md/);
3. 本示例需要使用DevEco Studio 3.1 Release (Build Version: 3.1.0.500)才可编译运行,需要配置"apl":"system_basic"才可安装成功;

代码示例

权限

ohos.permission.READ_IMAGEVIDEO、 ohos.permission.WRITE_IMAGEVIDEO

import photoAccessHelper from '@ohos.file.photoAccessHelper';
import dataSharePredicates from '@ohos.data.dataSharePredicates';

创建相册

async createAlbum(albumName: string): Promise<SimpleAlbumDataItem> {
    let newAlbum: SimpleAlbumDataItem = undefined;
    try {
      let album = await this.userFileMgr.createAlbum(albumName);
      newAlbum = new SimpleAlbumDataItem(MediaConstants.ALBUM_ID_USER, albumName, album.albumUri,
        '', '', MediaConstants.ALBUM_TYPE_USER, MediaConstants.ALBUM_SUBTYPE_USER_GENERIC);
    } catch (err) {
      Log.error(TAG, 'createAlbum failed with error: ' + err);
    }
    return newAlbum;
  }

查询相册

async getAlbums(fetchOption: photoAccessHelper.FetchOptions): Promise<photoAccessHelper.Album[]> {
    Log.info(TAG, 'getAlbums');
    let albums: photoAccessHelper.Album[] = [];
    try {
      albums = await this.userFileMgr.getAlbums(fetchOption);
      Log.info(TAG, 'getAlbums albums ' + albums.getCounts());
    } catch (err) {
      Log.error(TAG, 'getAlbums error:' + JSON.stringify(err));
    }
    Log.debug(TAG, 'getAlbums finish');
    return albums;
  }

通过相册类型查询媒体文件

async getAllMediaItemsByType(type: number, subType: number, albumFetchOption, fileFetchOption): Promise<photoAccessHelper.PhotoAsset[]> {
    let fileAssets: photoAccessHelper.PhotoAsset[] = [];
    let fetchResult: photoAccessHelper.FetchResult<photoAccessHelper.Album> = null;
    try {
      Log.info(TAG, 'getAllMediaItemsByUserFile');
      Log.info(TAG, 'type:' + type);
      Log.info(TAG, 'subType:' + subType);
      if (type === photoAccessHelper.AlbumType.USER && albumFetchOption != null) {
        Log.info(TAG, 'albumFetchOption != null');
        fetchResult = await this.userFileMgr.getAlbums(type, subType, albumFetchOption);
      } else {
        fetchResult = await this.userFileMgr.getAlbums(type, subType);
      }
      Log.info(TAG, 'get Album fetchResult, count: ' + fetchResult.getCount());
      for (let i = 0; i < fetchResult.getCount(); i++) {
        let albumAsset: photoAccessHelper.Album = await fetchResult.getObjectByPosition(i);
        let photoFetchResult: photoAccessHelper.FetchResult<photoAccessHelper.PhotoAsset> = null;
        try {
          photoFetchResult = await albumAsset.getAssets(fileFetchOption);
          for (let i = 0; i < photoFetchResult.getCount(); i++) {
            let photoAsset = await photoFetchResult.getObjectByPosition(i);
            fileAssets.push(photoAsset);
            Log.info(TAG, 'getPhotoAssets successfully, file displayName: ' + photoAsset.displayName);
          }
        } catch (err) {
          Log.info(TAG, 'get Album getPhotoAssets failed with err: ' + err);
        } finally {
          if (photoFetchResult != null) {
            photoFetchResult.close();
          }
        }
      }
    } catch (err) {
      Log.error(TAG, 'get Album fetchResult failed with err: ' + err);
    } finally {
      if (fetchResult != null) {
        fetchResult.close();
      }
    }
    Log.info(TAG, 'fileAssets: ' + fileAssets.length);
    return fileAssets;
  }

相册类型和子类型定义

AlbumType

枚举,相册类型,表示是用户相册还是系统预置相册。

系统能力:SystemCapability.FileManagement.PhotoAccessHelper.Core

名称 说明
USER 0 用户相册。
SYSTEM 1024 系统预置相册。
AlbumSubtype

枚举,相册子类型,表示具体的相册类型。

系统能力:SystemCapability.FileManagement.PhotoAccessHelper.Core

名称 说明
USER_GENERIC 1 用户相册。
FAVORITE 1025 收藏夹。
VIDEO 1026 视频相册。
HIDDEN 1027 隐藏相册。系统接口:此接口为系统接口。
TRASH 1028 回收站。系统接口:此接口为系统接口。
SCREENSHOT 1029 截屏和录屏相册。系统接口:此接口为系统接口。
CAMERA 1030 相机拍摄的照片和视频相册。系统接口:此接口为系统接口。
ANY 2147483647 任意相册。
无用

©著作权归作者所有,转载或内容合作请联系作者

您尚未登录,无法参与评论,登录后可以:
参与开源共建问题交流
认同或收藏高质量问答
获取积分成为开源共建先驱

Copyright   ©2023  OpenHarmony开发者论坛  京ICP备2020036654号-3 |技术支持 Discuz!

返回顶部