HarmonyOS官方文档保存图片到用户相册,报系统错误

想缓存(路径:/data/storage/el2/base/haps/entry/cache)里面的一张图片保存到用户相册,在已经给权限

(‘ohos.permission.READ_IMAGEVIDEO’和’ohos.permission.WRITE_IMAGEVIDEO’)的前提下。

按照官方文档:https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/photoaccesshelper-useralbum-guidelines-V5#ZH-CN_TOPIC_0000001914835246__%E6%B7%BB%E5%8A%A0%E5%9B%BE%E7%89%87%E5%92%8C%E8%A7%86%E9%A2%91%E5%88%B0%E7%94%A8%E6%88%B7%E7%9B%B8%E5%86%8C%E4%B8%AD

执行到以下代码段时直接报系统错误:

await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC, albumFetchOptions);
HarmonyOS
2024-08-22 20:13:58
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
zxjiu

ohos.permission.WRITE_IMAGEVIDEO为system_basic权限,走应用市场去申请ACL权限,或者通过安全控件savebutton创建媒体资源,相关资料请参考:https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/photoaccesshelper-useralbum-guidelines-V5

一.首先要在module.json5中添加:

"requestPermissions": [ 
{'name':'ohos.permission.INTERNET'}, 
{ 
  'name':'ohos.permission.READ_IMAGEVIDEO', 
"reason": '$string:reason_string', 
"usedScene": { 
  "abilities": [ 
  "EntryAbility" 
  ], 
  "when": "inuse" 
} 
} 
, { 
  'name':'ohos.permission.WRITE_IMAGEVIDEO', 
  "reason": '$string:app_name', 
  "usedScene": { 
    "abilities": [ 
    "EntryAbility" 
    ], 
    "when": "inuse" 
  } 
}],

注意:

1.添加完成之后点击右上角sync Now,

2.修改完权限之后要重新自动签名。

二.官方文档的案例是将第一个用户相册的第一个图片(手机上的图库,默认会有图片这个相册),存到目标相册albumName,(这个albumName是自定义的相册名)albumPredicates.equalTo(albumName, ‘albumName’);可以打开图库app,点击右上角加号,新建相册 名称为"1",点击确定,添加一张图片(不要选第一张图,不然后面执行代码,图片会覆盖,看不出效果)。然后将代码改为albumPredicates.equalTo(albumName, ‘1’);

三.唤起权限弹窗让用户授权。

const context = getContext(this); 
let permissions: Array<Permissions> = [ 
  'ohos.permission.READ_IMAGEVIDEO', 
  'ohos.permission.WRITE_IMAGEVIDEO', 
]; 
function alertPremission() { 
  // requestPermissionsFromUser会判断权限的授权状态来决定是否唤起弹窗 
  atManager.requestPermissionsFromUser(context, permissions).then((data: PermissionRequestResult) => { 
    let grantStatus: Array<number> = data.authResults; 
    let length: number = grantStatus.length; 
    for (let i = 0; i < length; i++) { 
      if (grantStatus[i] != 0) { 
        // todo:用户拒绝授权,提示用户必须授权才能访问当前页面的功能,并引导用户到系统设置中打开相应的权限 
        return; 
      } 
    } 
  }).catch((err: BusinessError) => { 
    console.error( ` Failed to request permissions from user. Code is ${err.code}, message is ${err.message}`); 
  }) 
}

index.ets完整代码:

import dataSharePredicates from '@ohos.data.dataSharePredicates'; 
import photoAccessHelper from '@ohos.file.photoAccessHelper'; 
import abilityAccessCtrl, { PermissionRequestResult, Permissions } from '@ohos.abilityAccessCtrl'; 
import { BusinessError } from '@kit.BasicServicesKit'; 
import { promptAction } from '@kit.ArkUI'; 
const context = getContext(this); 
let permissions: Array<Permissions> = [ 
  'ohos.permission.READ_IMAGEVIDEO', 
  'ohos.permission.WRITE_IMAGEVIDEO', 
]; 
let phAccessHelper = photoAccessHelper.getPhotoAccessHelper(context); 
let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager(); 
async function example() { 
  let albumPredicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); 
  let albumName: photoAccessHelper.AlbumKeys = photoAccessHelper.AlbumKeys.ALBUM_NAME; 
  albumPredicates.equalTo(albumName, '1'); 
  let albumFetchOptions: photoAccessHelper.FetchOptions = { 
    fetchColumns: [], 
    predicates: albumPredicates 
  }; 
  let photoPredicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); 
  let photoFetchOptions: photoAccessHelper.FetchOptions = { 
    fetchColumns: [], 
    predicates: photoPredicates 
  }; 
  try { 
    let albumFetchResult: photoAccessHelper.FetchResult<photoAccessHelper.Album> = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC, albumFetchOptions); 
    let album: photoAccessHelper.Album = await albumFetchResult.getFirstObject(); 
    console.info('getAlbums successfully, albumName: ' + album.albumName); 
    let photoFetchResult: photoAccessHelper.FetchResult<photoAccessHelper.PhotoAsset> = await phAccessHelper.getAssets(photoFetchOptions); 
    let photoAsset: photoAccessHelper.PhotoAsset = await photoFetchResult.getFirstObject(); 
    console.info('getAssets successfully, albumName: ' + photoAsset.displayName); 
    let albumChangeRequest: photoAccessHelper.MediaAlbumChangeRequest = new photoAccessHelper.MediaAlbumChangeRequest(album); 
    albumChangeRequest.addAssets([photoAsset]); 
    await phAccessHelper.applyChanges(albumChangeRequest); 
    console.info('succeed to add ' + photoAsset.displayName + ' to ' + album.albumName); 
    albumFetchResult.close(); 
    photoFetchResult.close(); 
    promptAction.showToast({message:'保存成功'}) 
  } catch (err) { 
    promptAction.showToast({message:'保存失败'}) 
    console.error('addAssets failed with err: ' + err); 
  } 
} 
function alertPremission() { 
  // requestPermissionsFromUser会判断权限的授权状态来决定是否唤起弹窗 
  atManager.requestPermissionsFromUser(context, permissions).then((data: PermissionRequestResult) => { 
    let grantStatus: Array<number> = data.authResults; 
    let length: number = grantStatus.length; 
    for (let i = 0; i < length; i++) { 
      if (grantStatus[i] != 0) { 
        // todo:用户拒绝授权,提示用户必须授权才能访问当前页面的功能,并引导用户到系统设置中打开相应的权限 
        return; 
      } 
    } 
  }).catch((err: BusinessError) => { 
    console.error( ` Failed to request permissions from user. Code is ${err.code}, message is ${err.message}`); 
  }) 
} 
@Entry 
@Component 
struct Index { 
  aboutToAppear(): void { 
    alertPremission() 
  } 
  build() { 
    Row() { 
      Column() { 
        Text('Hello World') 
          .fontSize(50) 
          .fontWeight(FontWeight.Bold) 
          .backgroundColor(Color.Yellow) 
          .onClick(()=>{ 
            example() 
          }) 
      }.width('100%') 
    }.height('100%') 
  } 
}

新建工程,将上述代码拷贝到Index.ets,然后添加module.json5,sync Now,重新自动授权, 图库新建相册 名称为"1",编译代码执行下,应该就能成功保存了。

分享
微博
QQ
微信
回复
2024-08-23 14:06:58
相关问题
HarmonyOS保存图片系统相册问题咨询
520浏览 • 1回复 待解决
HarmonyOS 保存图片相册问题
138浏览 • 1回复 待解决
HarmonyOS 保存图片相册权限问题
140浏览 • 1回复 待解决
如何保存网络图片相册
640浏览 • 1回复 待解决
求大佬告知如何保存图片相册
1016浏览 • 1回复 待解决
如何保存本地图片相册
921浏览 • 1回复 待解决
怎么实现保存网络图片相册功能?
133浏览 • 1回复 待解决
如何保存一张PNG图片相册
1743浏览 • 1回复 待解决
HarmonyOS图片保存相册问题
332浏览 • 1回复 待解决
鸿蒙开发保存页面相册
6287浏览 • 1回复 待解决
HarmonyOS 相册保存图片设置title报错
279浏览 • 1回复 待解决
推送服务系统错误1000900010
1616浏览 • 1回复 待解决
HarmonyOS如何把图片保存到手机相册
387浏览 • 1回复 待解决
获取网络图片保存相册
1290浏览 • 1回复 待解决