鸿蒙HarmonyOS系统相机Camera相关API使用

devtools/2024/11/27 12:35:35/

HarmonyOS下Camera相机相关API使用

准备工作

1. 导入camera接口

import { camera } from '@kit.CameraKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { common } from '@kit.AbilityKit';

2.获取cameraManager对象

getCameraManager(): camera.CameraManager {let cameraManager: camera.CameraManager = camera.getCameraManager(getContext(this));console.error("01 cameraManager."+cameraManager);return cameraManager;}

3.通过cameraManager类中的getSupportedCameras方法

getCameraDevices(cameraManager: camera.CameraManager): Array<camera.CameraDevice> {let cameraArray: Array<camera.CameraDevice> = cameraManager.getSupportedCameras();this.showContent = ''if (cameraArray != undefined && cameraArray.length > 0) {this.showContent = '支持的相机设备数量:' + cameraArray.lengthfor (let index = 0; index < cameraArray.length; index++) {console.info('cameraId : ' + cameraArray[index].cameraId); // 获取相机IDconsole.info('cameraPosition : ' + cameraArray[index].cameraPosition); // 获取相机位置console.info('cameraType : ' + cameraArray[index].cameraType); // 获取相机类型console.info('connectionType : ' + cameraArray[index].connectionType); // 获取相机连接类型this.showContent = 'cameraId:' + cameraArray[index].cameraId + '|cameraType:' + cameraArray[index].cameraType + '|connectionType:' + cameraArray[index].connectionType}return cameraArray;} else {console.error("cameraManager.getSupportedCameras error");this.errorContent = ' cameraManager.getSupportedCameras error'return [];}}

4.创建相机输入流

createInput(cameraDevice: camera.CameraDevice, cameraManager: camera.CameraManager): Promise<camera.CameraInput | undefined> {// 创建相机输入流let cameraInput: camera.CameraInput | undefined = undefined;try {cameraInput = cameraManager.createCameraInput(cameraDevice);} catch (error) {let err = error as BusinessError;console.error('Failed to createCameraInput errorCode = ' + err.code);}if (cameraInput === undefined) {return undefined;}// 监听cameraInput错误信息cameraInput.on('error', cameraDevice, (error: BusinessError) => {console.error(`Camera input error code: ${error.code}`);});// 打开相机await cameraInput.open();return cameraInput;
}

5.获取当前相机设备支持的所有输出流

 async getSupportedOutputCapability(cameraDevice: camera.CameraDevice, cameraManager: camera.CameraManager): Promise<camera.CameraOutputCapability | undefined> {// 创建相机输入流let cameraInput: camera.CameraInput | undefined = undefined;try {cameraInput = cameraManager.createCameraInput(cameraDevice);} catch (error) {let err = error as BusinessError;console.error('Failed to createCameraInput errorCode = ' + err.code);}if (cameraInput === undefined) {return undefined;}// 监听cameraInput错误信息cameraInput.on('error', cameraDevice, (error: BusinessError) => {console.error(`Camera input error code: ${error.code}`);this.errorContent = `Camera input error code: ${error.code}`});// 打开相机await cameraInput.open();// 获取相机设备支持的输出流能力let cameraOutputCapability: camera.CameraOutputCapability = cameraManager.getSupportedOutputCapability(cameraDevice);if (!cameraOutputCapability) {console.error("cameraManager.getSupportedOutputCapability error");return undefined;}console.info("outputCapability: " + JSON.stringify(cameraOutputCapability));this.showContent = 'cameraOutputCapability: ' + JSON.stringify(cameraOutputCapability)return cameraOutputCapability;}

6.创建一个会话

 getSession(cameraManager: camera.CameraManager): camera.Session | undefined {let session: camera.Session | undefined = undefined;try {session = cameraManager.createSession(camera.SceneMode.NORMAL_PHOTO) as camera.PhotoSession;} catch (error) {let err = error as BusinessError;console.error(`Failed to create the session instance. error: ${JSON.stringify(err)}`);}return session;
}

7.配置会话

 beginConfig(photoSession: camera.PhotoSession): void {try {photoSession.beginConfig();} catch (error) {let err = error as BusinessError;console.error(`Failed to beginConfig. error: ${JSON.stringify(err)}`);}
}

8.向会话中添加相机的输入流和输出流

 startSession(photoSession: camera.PhotoSession, cameraInput: camera.CameraInput, previewOutput: camera.PreviewOutput, photoOutput: camera.PhotoOutput): Promise<void> {try {photoSession.addInput(cameraInput);} catch (error) {let err = error as BusinessError;console.error(`Failed to addInput. error: ${JSON.stringify(err)}`);}try {photoSession.addOutput(previewOutput);} catch (error) {let err = error as BusinessError;console.error(`Failed to add previewOutput. error: ${JSON.stringify(err)}`);}try {photoSession.addOutput(photoOutput);} catch (error) {let err = error as BusinessError;console.error(`Failed to add photoOutput. error: ${JSON.stringify(err)}`);}try {await photoSession.commitConfig();} catch (error) {let err = error as BusinessError;console.error(`Failed to commitConfig. error: ${JSON.stringify(err)}`);}try {await photoSession.start();} catch (error) {let err = error as BusinessError;console.error(`Failed to start. error: ${JSON.stringify(err)}`);}
}

预览

1.创建Surface, 通过XComponent获取surfaceID

 XComponent({id: 'xComponentId',type: XComponentType.SURFACE,libraryname: 'nativerender',controller: this.mXComponentController}).width(this.isLand ? this.isVideoFullScreen ? '100%' : '75%' : CommonConstants.FULL_PERCENT).height(this.isLand ?this.isVideoFullScreen ? mScreenUtils.getScreenWidth() * this.videoHeight / this.videoWidth : mScreenUtils.getScreenWidth() * 0.75 * this.videoHeight / this.videoWidth :mScreenUtils.getScreenWidth() * this.videoHeight / this.videoWidth).onLoad(() => {// this.mXComponentController.setXComponentSurfaceSize({ surfaceWidth: 1920, surfaceHeight: 1080 })let surfaceID = this.mXComponentController.getXComponentSurfaceId()})

2.创建预览输出流

 getPreviewOutput(cameraManager: camera.CameraManager, cameraOutputCapability: camera.CameraOutputCapability, surfaceId: string): camera.PreviewOutput | undefined {let previewProfilesArray: Array<camera.Profile> = cameraOutputCapability.previewProfiles;let previewOutput: camera.PreviewOutput | undefined = undefined;try {previewOutput = cameraManager.createPreviewOutput(previewProfilesArray[0], surfaceId);} catch (error) {let err = error as BusinessError;console.error("Failed to create the PreviewOutput instance. error code: " + err.code);}return previewOutput;
}

3.输出预览流

startPreviewOutput(cameraManager: camera.CameraManager, previewOutput: camera.PreviewOutput): Promise<void> {let cameraArray: Array<camera.CameraDevice> = [];cameraArray = cameraManager.getSupportedCameras();if (cameraArray.length == 0) {console.error('no camera.');return;}// 获取支持的模式类型let sceneModes: Array<camera.SceneMode> = cameraManager.getSupportedSceneModes(cameraArray[0]);let isSupportPhotoMode: boolean = sceneModes.indexOf(camera.SceneMode.NORMAL_PHOTO) >= 0;if (!isSupportPhotoMode) {console.error('photo mode not support');return;}let cameraInput: camera.CameraInput | undefined = undefined;cameraInput = cameraManager.createCameraInput(cameraArray[0]);if (cameraInput === undefined) {console.error('cameraInput is undefined');return;}// 打开相机await cameraInput.open();let session: camera.PhotoSession = cameraManager.createSession(camera.SceneMode.NORMAL_PHOTO) as camera.PhotoSession;session.beginConfig();session.addInput(cameraInput);session.addOutput(previewOutput);await session.commitConfig();await session.start();
}

拍照

1.导入image接口

import { image } from '@kit.ImageKit';
import { camera } from '@kit.CameraKit';
import { fileIo as fs } from '@kit.CoreFileKit';
import { photoAccessHelper } from '@kit.MediaLibraryKit';
import { BusinessError } from '@kit.BasicServicesKit';

2. 创建拍照输出流

getPhotoOutput(cameraManager: camera.CameraManager, cameraOutputCapability: camera.CameraOutputCapability): camera.PhotoOutput | undefined {let photoProfilesArray: Array<camera.Profile> = cameraOutputCapability.photoProfiles;if (!photoProfilesArray) {console.error("createOutput photoProfilesArray == null || undefined");}let photoOutput: camera.PhotoOutput | undefined = undefined;try {photoOutput = cameraManager.createPhotoOutput(photoProfilesArray[0]);} catch (error) {let err = error as BusinessError;console.error(`Failed to createPhotoOutput. error: ${JSON.stringify(err)}`);}return photoOutput;
}

3.设置拍照回调,保存图片

 setPhotoOutputCb(photoOutput: camera.PhotoOutput) {
//设置回调之后,调用photoOutput的capture方法,就会将拍照的buffer回传到回调中photoOutput.on('photoAvailable', (errCode: BusinessError, photo: camera.Photo): void => {console.info('getPhoto start');console.info(`err: ${JSON.stringify(errCode)}`);if (errCode || photo === undefined) {console.error('getPhoto failed');return;}let imageObj: image.Image = photo.main;imageObj.getComponent(image.ComponentType.JPEG, (errCode: BusinessError, component: image.Component): void => {console.info('getComponent start');if (errCode || component === undefined) {console.error('getComponent failed');return;}let buffer: ArrayBuffer;if (component.byteBuffer) {buffer = component.byteBuffer;} else {console.error('byteBuffer is null');return;}// 如需要在图库中看到所保存的图片、视频资源,请使用用户无感的安全控件创建媒体资源。// buffer处理结束后需要释放该资源,如果未正确释放资源会导致后续拍照获取不到bufferimageObj.release(); });});
}

4.参数配置(闪光灯、变焦、焦距等)

 configuringSession(photoSession: camera.PhotoSession): void {// 判断设备是否支持闪光灯let flashStatus: boolean = false;try {flashStatus = photoSession.hasFlash();} catch (error) {let err = error as BusinessError;console.error(`Failed to hasFlash. error: ${JSON.stringify(err)}`);}console.info(`Returned with the flash light support status: ${flashStatus}`);if (flashStatus) {// 判断是否支持自动闪光灯模式let flashModeStatus: boolean = false;try {let status: boolean = photoSession.isFlashModeSupported(camera.FlashMode.FLASH_MODE_AUTO);flashModeStatus = status;} catch (error) {let err = error as BusinessError;console.error(`Failed to check whether the flash mode is supported. error: ${JSON.stringify(err)}`);}if (flashModeStatus) {// 设置自动闪光灯模式try {photoSession.setFlashMode(camera.FlashMode.FLASH_MODE_AUTO);} catch (error) {let err = error as BusinessError;console.error(`Failed to set the flash mode. error: ${JSON.stringify(err)}`);}}}// 判断是否支持连续自动变焦模式let focusModeStatus: boolean = false;try {let status: boolean = photoSession.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO);focusModeStatus = status;} catch (error) {let err = error as BusinessError;console.error(`Failed to check whether the focus mode is supported. error: ${JSON.stringify(err)}`);}if (focusModeStatus) {// 设置连续自动变焦模式try {photoSession.setFocusMode(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO);} catch (error) {let err = error as BusinessError;console.error(`Failed to set the focus mode. error: ${JSON.stringify(err)}`);}}// 获取相机支持的可变焦距比范围let zoomRatioRange: Array<number> = [];try {zoomRatioRange = photoSession.getZoomRatioRange();} catch (error) {let err = error as BusinessError;console.error(`Failed to get the zoom ratio range. error: ${JSON.stringify(err)}`);}if (zoomRatioRange.length <= 0 ) {return;}// 设置可变焦距比try {photoSession.setZoomRatio(zoomRatioRange[0]);} catch (error) {let err = error as BusinessError;console.error(`Failed to set the zoom ratio value. error: ${JSON.stringify(err)}`);}
}

5.拍照

主要通过photoOutput类的capture方法,执行拍照任务
capture(captureLocation: camera.Location, photoOutput: camera.PhotoOutput): void {let settings: camera.PhotoCaptureSetting = {quality: camera.QualityLevel.QUALITY_LEVEL_HIGH, // 设置图片质量高rotation: camera.ImageRotation.ROTATION_0, // 设置图片旋转角度0location: captureLocation, // 设置图片地理位置mirror: false  // 设置镜像使能开关(默认关)};photoOutput.capture(settings, (err: BusinessError) => {if (err) {console.error(`Failed to capture the photo. error: ${JSON.stringify(err)}`);this.errorContent = '`Failed to capture the photo. error: ' + JSON.stringify(err)return;}console.info('Callback invoked to indicate the photo capture request success.');this.showContent = ' photo capture success'});}

http://www.ppmy.cn/devtools/137386.html

相关文章

【工作总结】2. 链路追踪与 APM 系统构建

文章目录 0. 一些资料收集1. 背景 0. 一些资料收集 感谢开源社区资料&#xff0c;写在前面。 什么是 APM 系统&#xff1f;如何设计与实现&#xff1f; 1. 背景 近期&#xff0c;云原生微服务这块的业务搭建的差不多了。针对一些历史技术债准备拉出来解决。我这边就负责 链…

Vue.js基础——贼简单易懂!!(响应式 ref 和 reactive、v-on、v-show 和 v-if、v-for、v-bind)

Vue.js是一个渐进式JavaScript框架&#xff0c;用于构建用户界面。它专门设计用于Web应用程序&#xff0c;并专注于视图层。Vue允许开发人员创建可重用的组件&#xff0c;并轻松管理状态和数据绑定。它还提供了一个虚拟DOM系统&#xff0c;用于高效地渲染和重新渲染组件。Vue以…

C语言数据结构——详细讲解《栈》

C语言数据结构——详细讲解《栈》 前言一、栈的概念二、栈的定义三、栈的操作1.初始化栈2. 入栈操作3. 出栈操作4. 获取栈顶元素5. 检查栈是否为空6.释放栈内存 四、栈的例题五、本文的所有代码Stack.cStack,h最后一题代码 前言 在 C 语言编程中&#xff0c;数据结构是非常重要…

Java项目实战II基于微信小程序的电影院买票选座系统(开发文档+数据库+源码)

目录 一、前言 二、技术介绍 三、系统实现 四、核心代码 五、源码获取 全栈码农以及毕业设计实战开发&#xff0c;CSDN平台Java领域新星创作者&#xff0c;专注于大学生项目实战开发、讲解和毕业答疑辅导。获取源码联系方式请查看文末 一、前言 在数字化时代&#xff0c;…

SpringBoot集成minio,并实现文件上传

SpringBoot集成minio 什么是minioSpringBoot集成minio1、引入minio依赖2、配置Minio相关参数3、在代码里读取自定义的minio配置4、在minio配置类里,注册ConfigurationProperties实现文件上传到minio1、利用SpringMVC实现接口的异常全局处理2、返回文件路径给前端3、返回文件流…

使用 Django 构建支持 Kubernetes API 测试连接的 POST 接口

文章目录 使用 Django 构建支持 Kubernetes API 测试连接的 POST 接口功能需求使用 kubectl 获取 Token命令解析输出示例 完整代码实现Kubernetes API 客户端类功能说明 Django 接口视图关键点解析 路由配置 接口测试请求示例响应结果成功错误 优化建议1. 安全性2. 错误处理3. …

JavaWeb——请求响应(5/8)-请求:日期参数json参数(使用场景及封装类型、接收方式、在 Postman 中传递、在服务端接收)

目录 日期参数 使用场景及封装类型 接收方式 JSON 格式参数 在 Postman 中传递 在服务端接收 日期参数 使用场景及封装类型 在项目前端表单页面当中&#xff0c;经常会遇到一些日期、时间类型的参数&#xff0c;比如像用户的生日、入职日期、操作时间这样的请求参数。 …

VOLO实战:使用VOLO实现图像分类任务(二)

文章目录 训练部分导入项目使用的库设置随机因子设置全局参数图像预处理与增强读取数据设置Loss设置模型设置优化器和学习率调整策略设置混合精度&#xff0c;DP多卡&#xff0c;EMA定义训练和验证函数训练函数验证函数调用训练和验证方法 运行以及结果查看测试完整的代码 在上…