HarmonyOS 相册文件拷贝

从相册中选择照片,然后把照片拷贝到应用沙盒,进行图片编辑,最后上传到云端。

问题:把照片从相册中拷贝到应用沙盒失败,这个要怎么解决?

HarmonyOS
3天前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
zxjiu

可参考如下demo,拷贝照片到应用沙盒:

import picker from '@ohos.multimedia.cameraPicker'
import camera from '@ohos.multimedia.camera';
import common from '@ohos.app.ability.common';
import { BusinessError } from '@ohos.base';
import fileuri from '@ohos.file.fileuri';
import fs from '@ohos.file.fs';
import photoAccessHelper from '@ohos.file.photoAccessHelper';

let context = getContext(this) as common.Context;


class CameraPosition {
  cameraPosition: camera.CameraPosition
  saveUri: string

  constructor(cameraPosition: camera.CameraPosition, saveUri: string) {
    this.cameraPosition = cameraPosition
    this.saveUri = saveUri
  }
}

let pathDir = getContext().filesDir;
console.log('保存路径为'+pathDir)
let filePath = pathDir + '/picture.jpg'
fs.createRandomAccessFileSync(filePath, fs.OpenMode.CREATE);
let uri = fileuri.getUriFromPath(filePath);
async function photo() {
  try {
    let pickerProfile = new CameraPosition(camera.CameraPosition.CAMERA_POSITION_BACK, uri)
    let pickerResult: picker.PickerResult = await picker.pick(context,
      [picker.PickerMediaType.PHOTO, picker.PickerMediaType.VIDEO], pickerProfile);
    console.log("the pick pickerResult is:" + JSON.stringify(pickerResult));
  } catch (error) {
    let err = error as BusinessError;
    console.error(`the pick call failed. error code: ${err.code}`);
  }
}
async function picture() {
  let PhotoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
  PhotoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
  PhotoSelectOptions.maxSelectNumber = 1;
  let photoPicker = new photoAccessHelper.PhotoViewPicker();
  photoPicker.select(PhotoSelectOptions).then((PhotoSelectResult: photoAccessHelper.PhotoSelectResult) => {
    let photouri: Array<string> = PhotoSelectResult.photoUris
    let file = fs.openSync(photouri[0], fs.OpenMode.READ_ONLY)
    let file2 = fs.openSync(pathDir+'/picture2.jpg', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE)
    fs.copyFileSync(file.fd, file2.fd)
    fs.closeSync(file);
    fs.closeSync(file2);
  })
}


@Entry
@Component
export struct Index {
  build() {
    Column() {
      Button('选择并保存').onClick(() => {
        picture()
      })
      Button('拍照并保存').onClick(() => {
        photo()
      })
    }
  }
}
分享
微博
QQ
微信
回复
3天前
相关问题
HarmonyOS 读取相册文件问题咨询
28浏览 • 1回复 待解决
HarmonyOS 文件拷贝示例
25浏览 • 1回复 待解决
HarmonyOS 沙箱文件拷贝
58浏览 • 1回复 待解决
HarmonyOS选取并拷贝文件失败
435浏览 • 1回复 待解决
HarmonyOS拷贝拷贝
29浏览 • 1回复 待解决
HarmonyOS pixelmap深拷贝问题
658浏览 • 1回复 待解决
HarmonyOS ArkTS 如何实现浅拷贝
24浏览 • 1回复 待解决