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

news/2024/11/27 14:59:25/

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/news/1550371.html

相关文章

大模型面试题:能简单说下attention中存在的问吗?

我整理了1000道算法面试题&#xff1a; 获取 先说结论&#xff1a;从Attention is not all you need 这篇论文来看&#xff0c;单纯的不加残差连接且不加MLP的多层多头的Attention堆叠会导致模型输出的秩坍缩到rank-1的矩阵&#xff0c;也就是最后所有的表征都趋向于同一个向量…

训练的decoder模型文本长度不一致,一般设置为多大合适,需要覆盖最长的文本长度么

在训练解码器模型时,文本长度不一致是常见的情况,需要根据任务的特性和数据集的长度分布来设置合理的最大长度 (max_length)。以下是一些指导原则,帮助你设置合适的最大长度: 1. 是否需要覆盖最长文本长度 覆盖最长文本长度: 如果任务对完整性要求很高(例如生成数学公式、…

银行卡OCR 识别 API 接口如何用Java如何调用

银行卡 OCR 识别是利用光学字符识别技术&#xff0c;对银行卡上的卡号、有效期、持卡人姓名等信息进行快速、准确识别的过程。而银行卡 OCR 识别 API 接口则是将这种识别能力以接口的形式提供给开发者&#xff0c;使其能够轻松地集成到各种应用程序中&#xff0c;实现对银行卡信…

Mac——鼠标增强插件Mos

功能说明&#xff1a; 能够解决鼠标断续、不灵敏等鼠标问题。 下载地址&#xff1a; Mac——鼠标增强插件Mos

【面试题】2025年百度校招Java后端面试题

文章目录 前言一、网络IO1、服务器处理并发请求有哪几种方式&#xff1f;2、说一下select&#xff0c;poll&#xff0c;epoll的区别&#xff1f;3、Java 有一种现代的处理方式&#xff0c;属于异步I/O&#xff0c;是什么&#xff1f;redis&#xff0c;nginx&#xff0c;netty 是…

深度学习——激活函数

一、人工神经元 1.1 构建人工神经元 人工神经元接受多个输入信息&#xff0c;对它们进行加权求和&#xff0c;再经过激活函数处理&#xff0c;最后将这个结果输出。 1.2 组成部分 输入&#xff08;Inputs&#xff09;: 代表输入数据&#xff0c;通常用向量表示&#xff0c;每…

MySQL 索引详解

在数据库的世界中&#xff0c;索引就像是一本巨大书籍的目录&#xff0c;它能够极大地提高数据检索的效率。在 MySQL 中&#xff0c;索引的合理使用对于数据库的性能至关重要。本文将深入探讨 MySQL 索引的各个方面。 一、索引的概念与作用 1. 什么是索引&#xff1f; 索引是一…

[STM32]从零开始的STM32 FreeRTOS移植教程

一、前言 如果能看到这个教程的话&#xff0c;说明大家已经学习嵌入式有一段时间了。还记得嵌入式在大多数时候指的是什么吗&#xff1f;是的&#xff0c;我们所说的学习嵌入式大部分时候都是在学习嵌入式操作系统。从简单的一些任务状态机再到复杂一些的RTOS&#xff0c;再到最…