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

前言:

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

相关推荐
胖咕噜的稞达鸭11 天前
如何写好一个skill
人工智能·数码相机
Hello-FPGA11 天前
CameraLink相机模拟器 信号源加速激光雷达系统算法开发
数码相机
双翌视觉11 天前
机器视觉系统为何离不开光学滤光片?
人工智能·数码相机·视觉检测·制造
3DVisionary11 天前
XTDIC-VG视频引伸计技术原理解析:金属疲劳测试的“非接触革命“
python·数码相机·音视频·非接触测量·xtdic-vg·视频引伸计·金属疲劳测试
_李小白12 天前
【智能驾驶:视觉感知后处理 阅读笔记】Day4: 相机成像模型与畸变
笔记·数码相机
Hello-FPGA12 天前
基于VU13P VU系列FPGA的高性能CoaXpress 图像采集系统
数码相机
ctrl_v助手12 天前
VisionPro (R) QuickBuild相机的连接
服务器·笔记·数码相机·c#
工头阿乐12 天前
相机坐标系标定与外参矩阵求解
数码相机·线性代数·矩阵
问道财经12 天前
Pocket 4爆火,索尼富士慌了
数码相机
Hello-FPGA12 天前
CoaXPress 相机触发设置
数码相机