HarmonyOS 鸿蒙Next 如何把photoAccessHelper拿到的图片uri保存到本地沙箱

HarmonyOS 鸿蒙Next 如何把photoAccessHelper拿到的图片uri保存到本地沙箱

需求:通过photoPicker拿到的了图片的uris ,如何把这个uri保存到沙箱目录,需要传给服务器

4 回复
import { photoAccessHelper } from '@kit.MediaLibraryKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { image } from '@kit.ImageKit';
import fs from '@ohos.file.fs';
import { common } from '@kit.AbilityKit';
import fileIo from '@ohos.file.fs';
[@Entry](/user/Entry)
[@Component](/user/Component)
struct SavePixelMapToAlbum {
  [@State](/user/State) saveButtonOptions: SaveButtonOptions = {
    icon: SaveIconStyle.FULL_FILLED,
    text: SaveDescription.SAVE,
    buttonType: ButtonType.Capsule
  };
  async packToFile(pixelMap?: PixelMap): Promise<string> {
    // 获取应用文件路径
    let context = getContext(this) as common.UIAbilityContext;
    let filesDir: string = context.cacheDir;
    let picName = '/testimage' + new Date().getTime() + '.jpg'
    // 新建并打开文件
    let file = fs.openSync(filesDir + picName, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE);
    // let file = fileIo.openSync(filesDir + picName, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
    // 创建图像编码ImagePacker对象
    const imagePackerApi = image.createImagePacker();
    // // 设置编码输出流和编码参数。format为图像的编码格式;quality为图像质量,范围从0-100,100为最佳质量
    const options: image.PackingOption = { format: "image/jpeg", quality: 98 };
    await imagePackerApi.packToFile(pixelMap, file.fd, options)
    console.log(file.path);
    return file.path;
  }
  build() {
    Row() {
      Column() {
      Text('选择相册图片,并保存到沙盒路径')
        SaveButton(this.saveButtonOptions)
          .onClick(async (event, result: SaveButtonOnClickResult) => {
            if (result === SaveButtonOnClickResult.SUCCESS) {
              try {
                let PhotoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
                PhotoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
                PhotoSelectOptions.maxSelectNumber = 5;
                let photoPicker = new photoAccessHelper.PhotoViewPicker();
                photoPicker.select(PhotoSelectOptions)
                  .then(async (PhotoSelectResult: photoAccessHelper.PhotoSelectResult) => {
                    console.info('PhotoViewPicker.select successfully, PhotoSelectResult uri: ' +
                    JSON.stringify(PhotoSelectResult));
                   //获取相册图片URI
                    let filePath = PhotoSelectResult.photoUris[0]
                    let file = fileIo.openSync(filePath, fileIo.OpenMode.READ_ONLY)
                    //通过传入文件描述符来创建图片源实例
                    let imageSource: image.ImageSource = image.createImageSource(file.fd);
                    let pixelMap: image.PixelMap = await imageSource.createPixelMap();
                    //保存到沙盒路径
                    this.packToFile(pixelMap)
                  })
                  .catch((err: BusinessError) => {
                    console.error('PhotoViewPicker.select failed with err: ' + JSON.stringify(err));
                  });
              } catch (error) {
                let err: BusinessError = error as BusinessError;
                console.error('PhotoViewPicker failed with err: ' + JSON.stringify(err));
              }
            }
          })
      }
      .width('100%')
    }
    .height('100%')
  }
}

更多关于HarmonyOS 鸿蒙Next 如何把photoAccessHelper拿到的图片uri保存到本地沙箱的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


应该可以用持久化PersistentStorage储存吧,也可以写入文件

在HarmonyOS鸿蒙Next系统中,将通过photoAccessHelper获取的图片URI保存到本地沙箱,可以按照以下步骤操作:

  1. 获取URI:首先确保你已经通过photoAccessHelper成功获取到图片的URI。

  2. 创建MediaStore对象:利用MediaStore API,你可以方便地访问和管理媒体文件。

  3. 插入MediaStore:使用MediaStore.Images.Media.insertImage()方法,可以将图片数据插入到MediaStore中,同时这个操作也会将图片保存到设备的存储中。你需要提供图片的URI、MIME类型、文件名和描述等信息。注意,这里的URI应该是你通过photoAccessHelper获取到的图片的URI对应的文件内容。

  4. 获取保存后的URIinsertImage()方法会返回一个ContentResolver的URI,这个URI指向了新保存在MediaStore中的图片。

  5. 保存到沙箱:由于MediaStore的图片已经位于设备的公共存储中,如果你确实需要将其复制到应用的私有沙箱中,可以通过文件I/O操作(如使用FileInputStream和FileOutputStream)来实现。

请注意,在进行文件操作时,需要确保你的应用有相应的文件读写权限。

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

回到顶部