前言:
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';
class PhotoPicker {
private imgSrc:string = ''
//拍照
async takePhoto():Promise<string> {
const pickerResult = await cameraPicker.pick(getContext(),
[cameraPicker.PickerMediaType.PHOTO], {
cameraPosition: camera.CameraPosition.CAMERA_POSITION_BACK
});
this.saveImage(pickerResult.resultUri);
return this.imgSrc;
}
//从相册中选 photoAccessHelper版
async pickPhoto():Promise<string | void> {
const PhotoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
PhotoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
//选择图片数量
PhotoSelectOptions.maxSelectNumber = 1;
let photoPicker = new photoAccessHelper.PhotoViewPicker();
try {
const res = await photoPicker.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))
}
}
//存到应用缓存
private saveImage(src:string){
try {
const destPath = getContext(this).cacheDir
const fileType = src.split('.')[1]
const fileName = Date.now()
const path = `${destPath}/${fileName}.${fileType}`
const imgFile = fs.openSync(src,fs.OpenMode.READ_ONLY)
const tempFile = 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 as BusinessError;
console.info("img--[picker] Photo Save error = " + JSON.stringify(err));
}
}
}
export const photoPicker = new PhotoPicker()