文档管理中心

拍照实践(ArkTS)

在开发相机应用时,需要先申请相关权限。

当前示例提供完整的拍照流程介绍,方便开发者了解完整的接口调用顺序。

在参考以下示例前,建议开发者查看相机开发指导(ArkTS)的具体章节,了解设备输入、会话管理、拍照等单个流程。

开发流程

在获取到相机支持的输出流能力后,开始创建拍照流,开发流程如下。

完整示例

Context获取方式请参考:获取UIAbility的上下文信息。

如需要在图库中看到所保存的图片、视频资源,需要将其保存到媒体库,保存方式请参考:保存媒体库资源。

需要在photoOutput.on('photoAvailable')接口获取到buffer时,将buffer在安全控件中保存到媒体库。

收起
自动换行
深色代码主题
复制
  1. import { camera } from '@kit.CameraKit';
  2. import { image } from '@kit.ImageKit';
  3. import { BusinessError } from '@kit.BasicServicesKit';
  4. interface ShootingResources {
  5. cameraInput?: camera.CameraInput;
  6. previewOutput?: camera.PreviewOutput;
  7. photoOutput?: camera.PhotoOutput;
  8. photoSession?: camera.PhotoSession;
  9. }
  10. const resources: ShootingResources = {};
  11. function setPhotoOutputCb(photoOutput: camera.PhotoOutput): void {
  12. if (!photoOutput) {
  13. console.error('photoOutput is null');
  14. return;
  15. }
  16. // 设置回调之后,调用photoOutput的capture方法,就会将拍照的buffer回传到回调中。
  17. photoOutput?.on('photoAvailable', (err: BusinessError, photo: camera.Photo): void => {
  18. console.info('getPhoto start');
  19. console.error(`err: ${err}`);
  20. if (err && err.code != 0) {
  21. console.error('getPhoto failed');
  22. return;
  23. }
  24. if (!photo || !photo.main) {
  25. console.error('photo is null');
  26. return;
  27. }
  28. let imageObj = photo.main;
  29. imageObj.getComponent(image.ComponentType.JPEG, (errCode: BusinessError, component: image.Component): void => {
  30. console.info('getComponent start');
  31. if (errCode && errCode.code != 0 ) {
  32. console.error('getComponent failed');
  33. imageObj.release();
  34. return;
  35. }
  36. let buffer: ArrayBuffer;
  37. if (component && component.byteBuffer) {
  38. buffer = component.byteBuffer;
  39. } else {
  40. console.error('byteBuffer is null');
  41. imageObj.release();
  42. return;
  43. }
  44. // 如需要在图库中看到所保存的图片、视频资源,请使用用户无感的安全控件创建媒体资源。
  45. // buffer处理结束后需要释放该资源,如果未正确释放资源会导致后续拍照获取不到buffer。
  46. imageObj.release();
  47. });
  48. });
  49. }
  50. async function cameraShootingCase(context: Context, surfaceId: string): Promise<void> {
  51. try {
  52. // 创建CameraManager对象。
  53. let cameraManager: camera.CameraManager = camera.getCameraManager(context);
  54. if (!cameraManager) {
  55. console.error("camera.getCameraManager error");
  56. return;
  57. }
  58. // 监听相机状态变化。
  59. cameraManager.on('cameraStatus', (err: BusinessError, cameraStatusInfo: camera.CameraStatusInfo) => {
  60. if (err !== undefined && err.code !== 0) {
  61. console.error('cameraStatus with errorCode = ' + err.code);
  62. return;
  63. }
  64. console.info(`camera : ${cameraStatusInfo.camera.cameraId}`);
  65. console.info(`status: ${cameraStatusInfo.status}`);
  66. });
  67. // 获取相机列表。
  68. let cameraArray: Array<camera.CameraDevice> = cameraManager.getSupportedCameras();
  69. if (!cameraArray || cameraArray.length <= 0) {
  70. console.error("cameraManager.getSupportedCameras error");
  71. return;
  72. }
  73. for (let index = 0; index < cameraArray.length; index++) {
  74. console.info('cameraId : ' + cameraArray[index].cameraId); // 获取相机ID。
  75. console.info('cameraPosition : ' + cameraArray[index].cameraPosition); // 获取相机位置。
  76. console.info('cameraType : ' + cameraArray[index].cameraType); // 获取相机类型。
  77. console.info('connectionType : ' + cameraArray[index].connectionType); // 获取相机连接类型。
  78. }
  79. // 创建相机输入流。
  80. resources.cameraInput = cameraManager.createCameraInput(cameraArray[0]);
  81. if (!resources.cameraInput) {
  82. console.error('cameraInput is null');
  83. return;
  84. }
  85. // 监听cameraInput错误信息。
  86. let cameraDevice: camera.CameraDevice = cameraArray[0];
  87. resources.cameraInput.on('error', cameraDevice, (error: BusinessError) => {
  88. console.error(`Camera input error code: ${error.code}`);
  89. })
  90. // 打开相机。
  91. await resources.cameraInput.open();
  92. // 获取支持的模式类型。
  93. let sceneModes: Array<camera.SceneMode> = cameraManager.getSupportedSceneModes(cameraArray[0]);
  94. let isSupportPhotoMode: boolean = sceneModes.indexOf(camera.SceneMode.NORMAL_PHOTO) >= 0;
  95. if (!isSupportPhotoMode) {
  96. console.error('photo mode not support');
  97. releaseResources();
  98. return;
  99. }
  100. // 获取相机设备支持的输出流能力。
  101. let cameraOutputCap: camera.CameraOutputCapability = cameraManager.getSupportedOutputCapability(cameraArray[0], camera.SceneMode.NORMAL_PHOTO);
  102. if (!cameraOutputCap) {
  103. console.error("cameraManager.getSupportedOutputCapability error");
  104. return;
  105. }
  106. console.info("outputCapability: " + JSON.stringify(cameraOutputCap));
  107. let previewProfilesArray: Array<camera.Profile> = cameraOutputCap.previewProfiles;
  108. if (!previewProfilesArray || previewProfilesArray.length <= 0) {
  109. console.error("previewProfilesArray is null or []");
  110. releaseResources();
  111. return;
  112. }
  113. let photoProfilesArray: Array<camera.Profile> = cameraOutputCap.photoProfiles;
  114. if (!photoProfilesArray || photoProfilesArray.length <= 0) {
  115. console.error("photoProfilesArray is null or []");
  116. releaseResources();
  117. return;
  118. }
  119. // 创建预览输出流,其中参数 surfaceId 参考上文 XComponent 组件,预览流为XComponent组件提供的surface。
  120. resources.previewOutput = cameraManager.createPreviewOutput(previewProfilesArray[0], surfaceId);
  121. if (!resources.previewOutput) {
  122. console.error('previewOutput is null');
  123. releaseResources();
  124. return;
  125. }
  126. try {
  127. // 监听预览输出错误信息。
  128. resources.previewOutput.on('error', (error: BusinessError) => {
  129. console.error(`Preview output error code: ${error.code}`);
  130. });
  131. } catch (e) {
  132. console.error(`previewOutput.on call failed, error: ${JSON.stringify(e)}`);
  133. }
  134. // 创建拍照输出流。
  135. resources.photoOutput = cameraManager.createPhotoOutput(photoProfilesArray[0]);
  136. if (!resources.photoOutput) {
  137. console.error('photoOutput is null');
  138. releaseResources();
  139. return;
  140. }
  141. // 调用上面的回调函数来保存图片。
  142. setPhotoOutputCb(resources.photoOutput);
  143. // 创建会话。
  144. let photoSession = cameraManager.createSession(camera.SceneMode.NORMAL_PHOTO);
  145. if (!photoSession) {
  146. console.error('photoSession is null');
  147. releaseResources();
  148. return;
  149. }
  150. resources.photoSession = photoSession as camera.PhotoSession;
  151. try {
  152. // 监听session错误信息。
  153. resources.photoSession.on('error', (error: BusinessError) => {
  154. console.error(`Capture session error code: ${error.code}`);
  155. });
  156. } catch (e) {
  157. console.error(`photoSession.on call failed, error: ${JSON.stringify(e)}`);
  158. }
  159. // 开始配置会话。
  160. resources.photoSession.beginConfig();
  161. // 向会话中添加相机输入流。
  162. resources.photoSession.addInput(resources.cameraInput);
  163. // 向会话中添加预览输出流。
  164. resources.photoSession.addOutput(resources.previewOutput);
  165. // 向会话中添加拍照输出流。
  166. resources.photoSession.addOutput(resources.photoOutput);
  167. // 提交会话配置。
  168. await resources.photoSession.commitConfig();
  169. // 启动会话。
  170. await resources.photoSession.start()
  171. // 判断设备是否支持闪光灯。
  172. let flashStatus: boolean = false;
  173. flashStatus = resources.photoSession.hasFlash();
  174. console.info('Returned with the flash light support status:' + flashStatus);
  175. if (flashStatus) {
  176. // 判断是否支持自动闪光灯模式。
  177. let flashModeStatus: boolean = resources.photoSession.isFlashModeSupported(camera.FlashMode.FLASH_MODE_AUTO);
  178. if(flashModeStatus) {
  179. // 设置自动闪光灯模式。
  180. resources.photoSession.setFlashMode(camera.FlashMode.FLASH_MODE_AUTO);
  181. }
  182. }
  183. // 判断是否支持连续自动变焦模式。
  184. let focusModeStatus: boolean = resources.photoSession.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO);
  185. if (focusModeStatus) {
  186. // 设置连续自动变焦模式。
  187. resources.photoSession.setFocusMode(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO);
  188. }
  189. // 获取相机支持的可变焦距比范围。
  190. let zoomRatioRange: Array<number> = [];
  191. try {
  192. zoomRatioRange = resources.photoSession.getZoomRatioRange();
  193. } catch (error) {
  194. let err = error as BusinessError;
  195. console.error('Failed to get the zoom ratio range. errorCode = ' + err.code);
  196. }
  197. if (zoomRatioRange.length > 0) {
  198. // 设置可变焦距比。
  199. try {
  200. resources.photoSession.setZoomRatio(zoomRatioRange[0]);
  201. } catch (error) {
  202. let err = error as BusinessError;
  203. console.error('Failed to set the zoom ratio value. errorCode = ' + err.code);
  204. }
  205. }
  206. let photoCaptureSetting: camera.PhotoCaptureSetting = {
  207. quality: camera.QualityLevel.QUALITY_LEVEL_HIGH, // 设置图片质量高。
  208. rotation: camera.ImageRotation.ROTATION_0 // 设置图片旋转角度0。
  209. }
  210. // 使用当前拍照设置进行拍照。
  211. try {
  212. await resources.photoOutput.capture(photoCaptureSetting);
  213. } catch (error) {
  214. let err = error as BusinessError;
  215. console.error(`capture call failed, err: ${JSON.stringify(err)}`);
  216. }
  217. // 需要在拍照结束之后调用以下关闭相机和释放会话流程,避免拍照未结束就将会话释放。
  218. // 会话置空。
  219. resources.photoSession = undefined;
  220. } catch (error) {
  221. console.error(`cameraShootingCase call failed, error: ${JSON.stringify(error)}`);
  222. releaseResources();
  223. }
  224. }
  225. async function releaseResources(): Promise<void> {
  226. // 停止当前会话。
  227. await resources.photoSession?.stop().catch((e: BusinessError) => {console.error('停止会话失败:', e)});
  228. // 释放相机输入流。
  229. await resources.cameraInput?.close().catch((e: BusinessError) => {console.error('关闭相机失败:', e)});
  230. // 释放预览输出流。
  231. await resources.previewOutput?.release().catch((e: BusinessError) => {console.error('停止预览流失败:', e)});
  232. // 释放拍照输出流。
  233. await resources.photoOutput?.release().catch((e: BusinessError) => {console.error('停止拍照流失败:', e)});
  234. // 释放会话。
  235. await resources.photoSession?.release().catch((e: BusinessError) => {console.error('释放会话失败:', e)});
  236. }