如何保存图片到相册 HarmonyOS 鸿蒙Next

如何保存图片到相册 HarmonyOS 鸿蒙Next

可以使用安全控件中的保存控件,免去权限申请和权限请求等环节,获得临时授权,保存对应图片。参考代码如下:

import { photoAccessHelper } from '@kit.MediaLibraryKit';
import { fileIo } from '@kit.CoreFileKit';
import { common } from '@kit.AbilityKit';
import { promptAction } from '@kit.ArkUI';
import { BusinessError } from '@kit.BasicServicesKit';

async function savePhotoToGallery(context: common.UIAbilityContext) {
  let helper = photoAccessHelper.getPhotoAccessHelper(context);
  try {
    // onClick触发后10秒内通过createAsset接口创建图片文件,10秒后createAsset权限收回。
    let uri = await helper.createAsset(photoAccessHelper.PhotoType.IMAGE, 'jpg');
    // 使用uri打开文件,可以持续写入内容,写入过程不受时间限制
    let file = await fileIo.open(uri, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE);
    // $r('app.media.startIcon')需要替换为开发者所需的图像资源文件
    context.resourceManager.getMediaContent($r('app.media.startIcon').id, 0)
      .then(async value => {
        let media = value.buffer;
        // 写到媒体库文件中
        await fileIo.write(file.fd, media);
        await fileIo.close(file.fd);
        promptAction.showToast({ message: '已保存至相册!' });
      });
  }
  catch (error) {
    const err: BusinessError = error as BusinessError;
    console.error(`Failed to save photo. Code is ${err.code}, message is ${err.message}`);
  }
}

@Entry
@Component
struct Index {
  build() {
    Row() {
      Column({ space: 10 }) {
        // $r('app.media.startIcon')需要替换为开发者所需的图像资源文件
        Image($r('app.media.startIcon'))
          .height(400)
          .width('100%')

        SaveButton().onClick(async (event: ClickEvent, result: SaveButtonOnClickResult) => {
          if (result === SaveButtonOnClickResult.SUCCESS) {
            const context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
            // 免去权限申请和权限请求等环节,获得临时授权,保存对应图片
            savePhotoToGallery(context);
          } else {
            promptAction.showToast({ message: '设置权限失败!' })
          }
        })
      }
      .width('100%')
    }
    .height('100%')
    .backgroundColor(0xF1F3F5)
  }
}

参考链接

使用保存控件

存档图类型数据源


更多关于如何保存图片到相册 HarmonyOS 鸿蒙Next的实战教程也可以访问 https://www.itying.com/category-93-b0.html

2 回复

看到您已经找到解决方案,

链接

更多关于如何保存图片到相册 HarmonyOS 鸿蒙Next的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS(鸿蒙Next)中,保存图片到相册可以通过使用PhotoAccessHelper类实现。首先,确保在config.json文件中声明了ohos.permission.READ_MEDIAohos.permission.WRITE_MEDIA权限。然后,通过PhotoAccessHelper获取相册的访问权限,并使用createAsset方法将图片保存到相册中。具体步骤如下:

  1. 导入相关模块:

    import photoAccessHelper from '[@ohos](/user/ohos).file.photoAccessHelper';
    
  2. 获取PhotoAccessHelper实例:

    let phAccessHelper = photoAccessHelper.getPhotoAccessHelper(context);
    
  3. 创建图片文件并保存到相册:

    let photoAsset = await phAccessHelper.createAsset(photoAccessHelper.PhotoType.IMAGE, 'myImage.jpg', options);
    

其中,context是应用的上下文,options是保存图片时的配置选项。通过上述步骤,可以将图片保存到鸿蒙系统的相册中。

回到顶部