HarmonyOS 鸿蒙Next目前如何保存图片到相册,能给个demo吗

HarmonyOS 鸿蒙Next目前如何保存图片到相册,能给个demo吗

鸿蒙目前如何保存图片到相册,能给个demo吗

3 回复

鸿蒙端保存相册场景有2个方案

1. 组件 安全控件 savebutton https://developer.huawei.com/consumer/cn/doc/harmonyos-faqs-V5/faqs-image-13-V5

2.api方法 showAssetsCreationDialog 参考文档:https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V13/js-apis-photoaccesshelper-V13#showassetscreationdialog12

参考demo:

import { common } from '@kit.AbilityKit';
import { fileIo as fs, fileUri, ReadOptions, WriteOptions } from '@kit.CoreFileKit'
import { photoAccessHelper } from '@kit.MediaLibraryKit';
import json from '@ohos.util.json';

@Entry
@Component
struct Index {
  @State message: string = 'Hello World';

  filePath: string = '';

  build() {
    Column() {
      Button("复制文件到沙箱")
        .onClick(() => {
          console.log('开始复制文件到沙箱')
          this.copyFile()
          console.log('复制文件到沙箱完成')
        })
      Button('沙箱文件保存到相册')
        .onClick(()=>{
          console.log('开始沙箱文件保存到相册')
          this.syncToSysAlbum(photoAccessHelper.PhotoType.IMAGE,'png', this.filePath)
        })
      Button('沙箱文件保存到相册')
        .onClick(() => {
          console.log('开始沙箱文件保存到相册')
          this.example()
        })
    }
    .height('100%')
    .width('100%')
  }

  copyFile() {
    console.log("开发复制文件")
    let context = getContext(this) as common.UIAbilityContext;
    let srcFileDescriptor = context.resourceManager.getRawFdSync('background.png'); //这里填rawfile文件夹下的文件名(包括后缀)
    let stat = fs.statSync(srcFileDescriptor.fd)
    console.log(`stat isFile:${stat.isFile()}`);
    // 通过UIAbilityContext获取沙箱地址filesDir,以Stage模型为例
    let pathDir = context.filesDir;
    console.log("沙箱文件目录路径:", pathDir)
    let dstPath = pathDir + "/background.png";
    this.filePath = fileUri.getUriFromPath(dstPath)
    console.log("沙箱文件URI" + this.filePath);
    let dest = fs.openSync(dstPath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE)
    let bufsize = 4096
    let buf = new ArrayBuffer(bufsize)
    let off = 0, len = 0, readedLen = 0
    while (len = fs.readSync(srcFileDescriptor.fd, buf, { offset: srcFileDescriptor.offset + off, length: bufsize })) {
      readedLen += len
      fs.writeSync(dest.fd, buf, { offset: off, length: len })
      off = off + len
      if ((srcFileDescriptor.length - readedLen) < bufsize) {
        bufsize = srcFileDescriptor.length - readedLen
      }
    }
    fs.close(dest.fd)
  }

  async syncToSysAlbum(fileType: photoAccessHelper.PhotoType, extension: string, ...filePath: string[]) {
    //此处获取的phAccessHelper实例为全局对象,后续使用到phAccessHelper的地方默认为使用此处获取的对象,如未添加此段代码报phAccessHelper未定义的错误请自行添加
    let context = getContext(this);
    let phAccessHelper = photoAccessHelper.getPhotoAccessHelper(context);
    try {
      const srcFileUris: string[] = []
      filePath.forEach((path) => {
        srcFileUris.push(path)
      })
      const config: photoAccessHelper.PhotoCreationConfig[] = []
      config.push({
        title: 'backgr_ound', // 可选
        fileNameExtension: extension,
        photoType: fileType,
        subtype: photoAccessHelper.PhotoSubtype.DEFAULT, // 可选
      })
      console.log("syncToSysAlarm fileUri:" + json.stringify(srcFileUris) + ",config:" + json.stringify(config))
      const desFileUris = await phAccessHelper.showAssetsCreationDialog(srcFileUris, config)
      console.debug(`目标图片 uri is : ${JSON.stringify(desFileUris)}`)
      if (desFileUris.length > 0) {
        for (let index = 0; index < desFileUris.length; index++) {
          this.copyFileContentTo(srcFileUris[index], desFileUris[index])
        }
      }
    } catch (err) {
      console.log("syncToSysAlarm filePath:" + filePath + ",error:" + json.stringify(err))
    }
  }

  async example() {
    console.info('ShowAssetsCreationDialogDemo.');
    let context = getContext(this) as common.UIAbilityContext
    let phAccessHelper = photoAccessHelper.getPhotoAccessHelper(context);
    try {
      let srcFileUri: Array<string> = [this.filePath]
      console.debug(`图片 uri is : ${JSON.stringify(srcFileUri)}`)

      let photoCreationConfigs: Array<photoAccessHelper.PhotoCreationConfig> = [
        {
          title: 'background', // 可选
          fileNameExtension: 'png',
          photoType: photoAccessHelper.PhotoType.IMAGE,
          subtype: photoAccessHelper.PhotoSubtype.DEFAULT, // 可选
        }
      ];
      console.log("syncToSysAlarm fileUri:" + JSON.stringify(srcFileUri) + ",config:" +
      JSON.stringify(photoCreationConfigs))
      let desFileUris: Array<string> = await phAccessHelper.showAssetsCreationDialog(srcFileUri, photoCreationConfigs);
      console.debug(`目标图片 uri is : ${JSON.stringify(desFileUris)}`)


      if (desFileUris.length > 0) {
        for (let index = 0; index < desFileUris.length; index++) {
          this.copyFileContentTo(srcFileUri[index], desFileUris[index])
        }
      }

    } catch (err) {
      console.error('showAssetsCreationDialog failed, errCode is ' + err.code + ', errMsg is ' + err.message);
    }
  }

  /**
   * 复制文件内容到目标文件
   * @param srcFilePath 源文件路径
   * @param destFilePath 目标文件路径
   */
  copyFileContentTo(srcFilePath: string, destFilePath: string) {
    let srcFile = fs.openSync(srcFilePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE)
    let destFile = fs.openSync(destFilePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE)

    // 读取源文件内容并写入至目的文件
    let bufSize = 4096;
    let readSize = 0;
    let buf = new ArrayBuffer(bufSize);
    let readOptions: ReadOptions = {
      offset: readSize,
      length: bufSize
    };
    let readLen = fs.readSync(srcFile.fd, buf, readOptions);
    while (readLen > 0) {
      readSize += readLen;
      let writeOptions: WriteOptions = {
        length: readLen
      };
      fs.writeSync(destFile.fd, buf, writeOptions);
      readOptions.offset = readSize;
      readLen = fs.readSync(srcFile.fd, buf, readOptions);
    }
    // 关闭文件
    fs.closeSync(srcFile);
    fs.closeSync(destFile);
  }
}

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


可以参考下这篇博文:

HarmonyOS Next 屏幕截图 + 保存图片到系统相册 代码分享

https://developer.huawei.com/consumer/cn/blog/topic/03166979994620019

在HarmonyOS鸿蒙Next中保存图片到相册,可以通过以下步骤实现,并附上简要demo代码:

  1. 获取图片数据:确保已有图片的PixelMap对象或图片数据(如ArrayBuffer)。
  2. 转换图片格式:使用image.createImagePacker()将PixelMap对象压缩为JPEG等格式。
  3. 保存图片到设备存储:通过文件I/O操作,使用fs模块将压缩后的图像数据写入到设备的临时或持久化存储中。
  4. 添加到系统相册:利用photoAccessHelper.showAssetsCreationDialog() API,传入源文件的URI和图片创建配置(如文件名、类型等),将图片添加到系统相册。

以下是简要demo代码:

let context = getContext(this) as common.UIAbilityContext;
let phAccessHelper = photoAccessHelper.getPhotoAccessHelper(context);
let srcFileUri = [fileUri.getUriFromPath(yourImagePath)]; // yourImagePath是图片路径
let photoCreationConfigs = [{
    title: fileName,
    fileNameExtension: 'jpg',
    photoType: photoAccessHelper.PhotoType.IMAGE,
    subtype: photoAccessHelper.PhotoSubtype.DEFAULT
}];
phAccessHelper.showAssetsCreationDialog(srcFileUri, photoCreationConfigs).then(desFileUris => {
    console.log('图片已保存到相册', desFileUris);
});

如果问题依旧没法解决请联系官网客服,官网地址是:https://www.itying.com/category-93-b0.html

回到顶部
AI 助手
你好,我是IT营的 AI 助手
您可以尝试点击下方的快捷入口开启体验!