1# 拍照实践(ArkTS) 2 3在开发相机应用时,需要先参考开发准备[申请相关权限](camera-preparation.md)。 4 5当前示例提供完整的拍照流程介绍,方便开发者了解完整的接口调用顺序。 6 7在参考以下示例前,建议开发者查看[相机开发指导(ArkTS)](camera-preparation.md)的具体章节,了解[设备输入](camera-device-input.md)、[会话管理](camera-session-management.md)、[拍照](camera-shooting.md)等单个流程。 8 9## 开发流程 10 11在获取到相机支持的输出流能力后,开始创建拍照流,开发流程如下。 12 13 14 15## 完整示例 16 17Context获取方式请参考:[获取UIAbility的上下文信息](../../application-models/uiability-usage.md#获取uiability的上下文信息)。 18 19如需要在图库中看到所保存的图片、视频资源,需要将其保存到媒体库,保存方式请参考:[保存媒体库资源](../medialibrary/photoAccessHelper-savebutton.md)。 20 21需要在[photoOutput.on('photoAvailable')](../../reference/apis-camera-kit/js-apis-camera.md#onphotoavailable11)接口获取到buffer时,将buffer在安全控件中保存到媒体库。 22```ts 23import { camera } from '@kit.CameraKit'; 24import { image } from '@kit.ImageKit'; 25import { BusinessError } from '@kit.BasicServicesKit'; 26 27function setPhotoOutputCb(photoOutput: camera.PhotoOutput): void { 28 //设置回调之后,调用photoOutput的capture方法,就会将拍照的buffer回传到回调中。 29 photoOutput.on('photoAvailable', (errCode: BusinessError, photo: camera.Photo): void => { 30 console.info('getPhoto start'); 31 console.info(`err: ${errCode}`); 32 if (errCode || photo === undefined) { 33 console.error('getPhoto failed'); 34 return; 35 } 36 let imageObj = photo.main; 37 imageObj.getComponent(image.ComponentType.JPEG, (errCode: BusinessError, component: image.Component): void => { 38 console.info('getComponent start'); 39 if (errCode || component === undefined) { 40 console.error('getComponent failed'); 41 return; 42 } 43 let buffer: ArrayBuffer; 44 if (component.byteBuffer) { 45 buffer = component.byteBuffer; 46 } else { 47 console.error('byteBuffer is null'); 48 return; 49 } 50 51 // 如需要在图库中看到所保存的图片、视频资源,请使用用户无感的安全控件创建媒体资源。 52 53 // buffer处理结束后需要释放该资源,如果未正确释放资源会导致后续拍照获取不到buffer。 54 imageObj.release(); 55 }); 56 }); 57} 58 59async function cameraShootingCase(context: Context, surfaceId: string): Promise<void> { 60 // 创建CameraManager对象。 61 let cameraManager: camera.CameraManager = camera.getCameraManager(context); 62 if (!cameraManager) { 63 console.error("camera.getCameraManager error"); 64 return; 65 } 66 // 监听相机状态变化。 67 cameraManager.on('cameraStatus', (err: BusinessError, cameraStatusInfo: camera.CameraStatusInfo) => { 68 if (err !== undefined && err.code !== 0) { 69 console.error('cameraStatus with errorCode = ' + err.code); 70 return; 71 } 72 console.info(`camera : ${cameraStatusInfo.camera.cameraId}`); 73 console.info(`status: ${cameraStatusInfo.status}`); 74 }); 75 76 // 获取相机列表。 77 let cameraArray: Array<camera.CameraDevice> = cameraManager.getSupportedCameras(); 78 if (cameraArray.length <= 0) { 79 console.error("cameraManager.getSupportedCameras error"); 80 return; 81 } 82 83 for (let index = 0; index < cameraArray.length; index++) { 84 console.info('cameraId : ' + cameraArray[index].cameraId); // 获取相机ID。 85 console.info('cameraPosition : ' + cameraArray[index].cameraPosition); // 获取相机位置。 86 console.info('cameraType : ' + cameraArray[index].cameraType); // 获取相机类型。 87 console.info('connectionType : ' + cameraArray[index].connectionType); // 获取相机连接类型。 88 } 89 90 // 创建相机输入流。 91 let cameraInput: camera.CameraInput | undefined = undefined; 92 try { 93 cameraInput = cameraManager.createCameraInput(cameraArray[0]); 94 } catch (error) { 95 let err = error as BusinessError; 96 console.error('Failed to createCameraInput errorCode = ' + err.code); 97 } 98 if (cameraInput === undefined) { 99 return; 100 } 101 102 // 监听cameraInput错误信息。 103 let cameraDevice: camera.CameraDevice = cameraArray[0]; 104 cameraInput.on('error', cameraDevice, (error: BusinessError) => { 105 console.error(`Camera input error code: ${error.code}`); 106 }) 107 108 // 打开相机。 109 await cameraInput.open(); 110 111 // 获取支持的模式类型。 112 let sceneModes: Array<camera.SceneMode> = cameraManager.getSupportedSceneModes(cameraArray[0]); 113 let isSupportPhotoMode: boolean = sceneModes.indexOf(camera.SceneMode.NORMAL_PHOTO) >= 0; 114 if (!isSupportPhotoMode) { 115 console.error('photo mode not support'); 116 return; 117 } 118 // 获取相机设备支持的输出流能力。 119 let cameraOutputCap: camera.CameraOutputCapability = cameraManager.getSupportedOutputCapability(cameraArray[0], camera.SceneMode.NORMAL_PHOTO); 120 if (!cameraOutputCap) { 121 console.error("cameraManager.getSupportedOutputCapability error"); 122 return; 123 } 124 console.info("outputCapability: " + JSON.stringify(cameraOutputCap)); 125 126 let previewProfilesArray: Array<camera.Profile> = cameraOutputCap.previewProfiles; 127 if (!previewProfilesArray) { 128 console.error("createOutput previewProfilesArray == null || undefined"); 129 } 130 131 let photoProfilesArray: Array<camera.Profile> = cameraOutputCap.photoProfiles; 132 if (!photoProfilesArray) { 133 console.error("createOutput photoProfilesArray == null || undefined"); 134 } 135 136 // 创建预览输出流,其中参数 surfaceId 参考上文 XComponent 组件,预览流为XComponent组件提供的surface。 137 let previewOutput: camera.PreviewOutput | undefined = undefined; 138 try { 139 previewOutput = cameraManager.createPreviewOutput(previewProfilesArray[0], surfaceId); 140 } catch (error) { 141 let err = error as BusinessError; 142 console.error(`Failed to create the PreviewOutput instance. error code: ${err.code}`); 143 } 144 if (previewOutput === undefined) { 145 return; 146 } 147 // 监听预览输出错误信息。 148 previewOutput.on('error', (error: BusinessError) => { 149 console.error(`Preview output error code: ${error.code}`); 150 }); 151 152 // 创建拍照输出流。 153 let photoOutput: camera.PhotoOutput | undefined = undefined; 154 try { 155 photoOutput = cameraManager.createPhotoOutput(photoProfilesArray[0]); 156 } catch (error) { 157 let err = error as BusinessError; 158 console.error('Failed to createPhotoOutput errorCode = ' + err.code); 159 } 160 if (photoOutput === undefined) { 161 return; 162 } 163 164 //调用上面的回调函数来保存图片。 165 setPhotoOutputCb(photoOutput); 166 167 //创建会话。 168 let photoSession: camera.PhotoSession | undefined = undefined; 169 try { 170 photoSession = cameraManager.createSession(camera.SceneMode.NORMAL_PHOTO) as camera.PhotoSession; 171 } catch (error) { 172 let err = error as BusinessError; 173 console.error('Failed to create the session instance. errorCode = ' + err.code); 174 } 175 if (photoSession === undefined) { 176 return; 177 } 178 // 监听session错误信息。 179 photoSession.on('error', (error: BusinessError) => { 180 console.error(`Capture session error code: ${error.code}`); 181 }); 182 183 // 开始配置会话。 184 try { 185 photoSession.beginConfig(); 186 } catch (error) { 187 let err = error as BusinessError; 188 console.error('Failed to beginConfig. errorCode = ' + err.code); 189 } 190 191 // 向会话中添加相机输入流。 192 try { 193 photoSession.addInput(cameraInput); 194 } catch (error) { 195 let err = error as BusinessError; 196 console.error('Failed to addInput. errorCode = ' + err.code); 197 } 198 199 // 向会话中添加预览输出流。 200 try { 201 photoSession.addOutput(previewOutput); 202 } catch (error) { 203 let err = error as BusinessError; 204 console.error('Failed to addOutput(previewOutput). errorCode = ' + err.code); 205 } 206 207 // 向会话中添加拍照输出流。 208 try { 209 photoSession.addOutput(photoOutput); 210 } catch (error) { 211 let err = error as BusinessError; 212 console.error('Failed to addOutput(photoOutput). errorCode = ' + err.code); 213 } 214 215 // 提交会话配置。 216 await photoSession.commitConfig(); 217 218 // 启动会话。 219 await photoSession.start().then(() => { 220 console.info('Promise returned to indicate the session start success.'); 221 }); 222 // 判断设备是否支持闪光灯。 223 let flashStatus: boolean = false; 224 try { 225 flashStatus = photoSession.hasFlash(); 226 } catch (error) { 227 let err = error as BusinessError; 228 console.error('Failed to hasFlash. errorCode = ' + err.code); 229 } 230 console.info('Returned with the flash light support status:' + flashStatus); 231 232 if (flashStatus) { 233 // 判断是否支持自动闪光灯模式。 234 let flashModeStatus: boolean = false; 235 try { 236 let status: boolean = photoSession.isFlashModeSupported(camera.FlashMode.FLASH_MODE_AUTO); 237 flashModeStatus = status; 238 } catch (error) { 239 let err = error as BusinessError; 240 console.error('Failed to check whether the flash mode is supported. errorCode = ' + err.code); 241 } 242 if(flashModeStatus) { 243 // 设置自动闪光灯模式。 244 try { 245 photoSession.setFlashMode(camera.FlashMode.FLASH_MODE_AUTO); 246 } catch (error) { 247 let err = error as BusinessError; 248 console.error('Failed to set the flash mode. errorCode = ' + err.code); 249 } 250 } 251 } 252 253 // 判断是否支持连续自动变焦模式。 254 let focusModeStatus: boolean = false; 255 try { 256 let status: boolean = photoSession.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO); 257 focusModeStatus = status; 258 } catch (error) { 259 let err = error as BusinessError; 260 console.error('Failed to check whether the focus mode is supported. errorCode = ' + err.code); 261 } 262 263 if (focusModeStatus) { 264 // 设置连续自动变焦模式。 265 try { 266 photoSession.setFocusMode(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO); 267 } catch (error) { 268 let err = error as BusinessError; 269 console.error('Failed to set the focus mode. errorCode = ' + err.code); 270 } 271 } 272 273 // 获取相机支持的可变焦距比范围。 274 let zoomRatioRange: Array<number> = []; 275 try { 276 zoomRatioRange = photoSession.getZoomRatioRange(); 277 } catch (error) { 278 let err = error as BusinessError; 279 console.error('Failed to get the zoom ratio range. errorCode = ' + err.code); 280 } 281 if (zoomRatioRange.length <= 0) { 282 return; 283 } 284 // 设置可变焦距比。 285 try { 286 photoSession.setZoomRatio(zoomRatioRange[0]); 287 } catch (error) { 288 let err = error as BusinessError; 289 console.error('Failed to set the zoom ratio value. errorCode = ' + err.code); 290 } 291 let photoCaptureSetting: camera.PhotoCaptureSetting = { 292 quality: camera.QualityLevel.QUALITY_LEVEL_HIGH, // 设置图片质量高。 293 rotation: camera.ImageRotation.ROTATION_0 // 设置图片旋转角度0。 294 } 295 // 使用当前拍照设置进行拍照。 296 photoOutput.capture(photoCaptureSetting, (err: BusinessError) => { 297 if (err) { 298 console.error(`Failed to capture the photo ${err.message}`); 299 return; 300 } 301 console.info('Callback invoked to indicate the photo capture request success.'); 302 }); 303 304 // 需要在拍照结束之后调用以下关闭相机和释放会话流程,避免拍照未结束就将会话释放。 305 // 停止当前会话。 306 await photoSession.stop(); 307 308 // 释放相机输入流。 309 await cameraInput.close(); 310 311 // 释放预览输出流。 312 await previewOutput.release(); 313 314 // 释放拍照输出流。 315 await photoOutput.release(); 316 317 // 释放会话。 318 await photoSession.release(); 319 320 // 会话置空。 321 photoSession = undefined; 322} 323``` 324 325