鸿蒙实现相机拍照及相册选择照片

前言:

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.photoUris0)

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()

相关推荐
shoufeipin90hou19 小时前
光选机的“除尘与风选“配套边界:分选精度上不去,可能问题不在相机
数码相机·计算机视觉
大熊背1 天前
《Exposure Evaluation Method Based on Histogram Statistics》文献详细总结
数码相机·自动曝光·三阶矩·样本偏度
李游Leo1 天前
HarmonyOS 7 + Hvigor-module.json5:权限增量审计与隐私声明一致性门禁【鸿蒙心迹】
数码相机·华为·harmonyos
高升说2 天前
深度相机接口选型:MIPI、USB3 与 GigE 的带宽估算与工程取舍
网络·人工智能·数码相机
高升说2 天前
户外强光下的深度相机:940nm 窄带与曝光策略
人工智能·数码相机
LabVIEW开发3 天前
LabVIEW 驱动 Andor 相机:从 SDK 到出图
数码相机·labview·labview知识·labview功能·labview程序
高升说3 天前
避障相机与激光雷达的硬件融合:时基、外参、算力与布局的工程实现
人工智能·数码相机
hahaha60164 天前
自动白平衡 & 手动白平衡
数码相机
钒星物联网4 天前
林区没信号,红外相机怎么把照片实时送出来?
数码相机·数据传输·卫星通信·红外相机·自组网·宽带卫星
特创数字科技4 天前
【uni-app x】告别系统相机限制!三端通用自定义相机组件:任意布局、静默拍照、录像、水印叠加、连拍回图一次搞定
前端·数码相机·uni-app