前言:
1.如果你的应用不是存储类型或者相机拍照类型,你就需要用 @kit.CameraKit Api 实现相机拍照和相册选择照片功能,如果你不用这个的话,你使用 picker.PhotoViewPicker ,你就需要申请权限,那你提交应用审核的时候就会被拒,说你使用了敏感权限。
2.以下是自己封装的一个工具类,可直接导入使用
import { camera, cameraPicker } from'@kit.CameraKit';
import { photoAccessHelper } from'@kit.MediaLibraryKit';
import fs from'@ohos.file.fs';
import { BusinessError } from'@kit.BasicServicesKit';
classPhotoPicker {
privateimgSrc:string = ''
//拍照
asynctakePhoto():Promise<string> {
const pickerResult = awaitcameraPicker.pick(getContext(),
[cameraPicker.PickerMediaType.PHOTO], {
cameraPosition: camera.CameraPosition.CAMERA_POSITION_BACK
});
this.saveImage(pickerResult.resultUri);
return this.imgSrc;
}
//从相册中选 photoAccessHelper版
asyncpickPhoto():Promise<string | void> {
const PhotoSelectOptions = newphotoAccessHelper.PhotoSelectOptions();
PhotoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
//选择图片数量
PhotoSelectOptions.maxSelectNumber = 1;
let photoPicker = newphotoAccessHelper.PhotoViewPicker();
try{
const res = awaitphotoPicker.select(PhotoSelectOptions)
if(res.photoUris.length <= 0) {
return
}
this.saveImage(res.photoUris[0])
return this.imgSrc;
} catch(e) {
console.log('img----err--',JSON.stringify(e))
}
}
//存到应用缓存
privatesaveImage(src:string){
try{
const destPath = getContext(this).cacheDir
constfileType = src.split('.')[1]
constfileName = Date.now()
constpath = `{destPath}/{fileName}.${fileType}`
constimgFile = fs.openSync(src,fs.OpenMode.READ_ONLY)
consttempFile = fs.openSync(path,fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE)
// 拷贝
fs.copyFileSync(imgFile.fd,tempFile.fd)
fs.close(imgFile)
fs.close(tempFile)
// 从沙箱中获取图片路径
// this.imgSrc = fileUri.getUriFromPath(path)
this.imgSrc = path
} catch(e) {
let err: BusinessError = e asBusinessError;
console.info("img--[picker] Photo Save error = " + JSON.stringify(err));
}
}
}
export const photoPicker = newPhotoPicker()