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