• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Photo Capture (ArkTS)
2<!--Kit: Camera Kit-->
3<!--Subsystem: Multimedia-->
4<!--Owner: @qano-->
5<!--SE: @leo_ysl-->
6<!--TSE: @xchaosioda-->
7
8Photo capture is an important function of the camera application. Based on the complex logic of the camera hardware, the camera module provides APIs for you to set information such as resolution, flash, focal length, photo quality, and rotation angle.
9
10## How to Develop
11
12Read [Module Description](../../reference/apis-camera-kit/arkts-apis-camera.md) for the API reference.
13
141. Import the image module. The APIs provided by this module are used to obtain the surface ID and create a photo output stream.
15
16   ```ts
17   import { image } from '@kit.ImageKit';
18   import { camera } from '@kit.CameraKit';
19   import { fileIo as fs } from '@kit.CoreFileKit';
20   import { photoAccessHelper } from '@kit.MediaLibraryKit';
21   import { BusinessError } from '@kit.BasicServicesKit';
22   ```
23
242. Create a photo output stream.
25
26   Obtain the photo output streams supported by the current device from **photoProfiles** in the [CameraOutputCapability](../../reference/apis-camera-kit/arkts-apis-camera-i.md#cameraoutputcapability) class, and then call [createPhotoOutput](../../reference/apis-camera-kit/arkts-apis-camera-CameraManager.md#createphotooutput11) to pass in a supported output stream and the surface ID obtained in step 1 to create a photo output stream.
27
28   ```ts
29   function getPhotoOutput(cameraManager: camera.CameraManager, cameraOutputCapability: camera.CameraOutputCapability): camera.PhotoOutput | undefined {
30     let photoProfilesArray: Array<camera.Profile> = cameraOutputCapability.photoProfiles;
31     if (!photoProfilesArray) {
32       console.error("createOutput photoProfilesArray == null || undefined");
33     }
34     let photoOutput: camera.PhotoOutput | undefined = undefined;
35     try {
36       photoOutput = cameraManager.createPhotoOutput(photoProfilesArray[0]);
37     } catch (error) {
38       let err = error as BusinessError;
39       console.error(`Failed to createPhotoOutput. error: ${err}`);
40     }
41     return photoOutput;
42   }
43   ```
44
453. Set the callback for the **'photoAvailable'** event and save the photo buffer as an image.
46
47    For details about how to obtain the context, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability).
48
49    To view the saved images and videos in Gallery, you must save them to the media library. For details, see [Saving Media Assets](../medialibrary/photoAccessHelper-savebutton.md).
50
51    Specifically, when [photoOutput.on('photoAvailable')](../../reference/apis-camera-kit/arkts-apis-camera-PhotoOutput.md#onphotoavailable11) is called and a buffer is obtained, the buffer must be stored in the security component to the media library.
52   ```ts
53   function setPhotoOutputCb(photoOutput: camera.PhotoOutput, context: Context) {
54   // After the callback is set, call capture() of photoOutput to transfer the photo buffer back to the callback.
55     photoOutput.on('photoAvailable', (errCode: BusinessError, photo: camera.Photo): void => {
56        console.info('getPhoto start');
57        console.error(`err: ${errCode}`);
58        if (errCode || photo === undefined) {
59          console.error('getPhoto failed');
60          return;
61        }
62        let imageObj: image.Image = photo.main;
63        imageObj.getComponent(image.ComponentType.JPEG, (errCode: BusinessError, component: image.Component): void => {
64          console.info('getComponent start');
65          if (errCode || component === undefined) {
66            console.error('getComponent failed');
67            return;
68          }
69          let buffer: ArrayBuffer;
70          if (component.byteBuffer) {
71            buffer = component.byteBuffer;
72          } else {
73            console.error('byteBuffer is null');
74            return;
75          }
76          // To view the saved image and video resources in Gallery, use a security component to create media assets.
77
78          // After the buffer processing is complete, the buffer must be released. Otherwise, no buffer is available for subsequent photo capture.
79          imageObj.release();
80        });
81      });
82   }
83   ```
84
854. Set camera parameters.
86
87   You can set camera parameters to adjust photo capture functions, including the flash, zoom ratio, and focal length.
88
89   ```ts
90   function configuringSession(photoSession: camera.PhotoSession): void {
91     // Check whether the camera has flash.
92     let flashStatus: boolean = false;
93     try {
94       flashStatus = photoSession.hasFlash();
95     } catch (error) {
96       let err = error as BusinessError;
97       console.error(`Failed to hasFlash. error: ${err}`);
98     }
99     console.info(`Returned with the flash light support status: ${flashStatus}`);
100     if (flashStatus) {
101       // Check whether the auto flash mode is supported.
102       let flashModeStatus: boolean = false;
103       try {
104         let status: boolean = photoSession.isFlashModeSupported(camera.FlashMode.FLASH_MODE_AUTO);
105         flashModeStatus = status;
106       } catch (error) {
107         let err = error as BusinessError;
108         console.error(`Failed to check whether the flash mode is supported. error: ${err}`);
109       }
110       if (flashModeStatus) {
111         // Set the flash mode to auto.
112         try {
113           photoSession.setFlashMode(camera.FlashMode.FLASH_MODE_AUTO);
114         } catch (error) {
115           let err = error as BusinessError;
116           console.error(`Failed to set the flash mode. error: ${err}`);
117         }
118       }
119     }
120     // Check whether the continuous auto focus is supported.
121     let focusModeStatus: boolean = false;
122     try {
123       let status: boolean = photoSession.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO);
124       focusModeStatus = status;
125     } catch (error) {
126       let err = error as BusinessError;
127       console.error(`Failed to check whether the focus mode is supported. error: ${err}`);
128     }
129     if (focusModeStatus) {
130       // Set the focus mode to continuous auto focus.
131       try {
132         photoSession.setFocusMode(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO);
133       } catch (error) {
134         let err = error as BusinessError;
135         console.error(`Failed to set the focus mode. error: ${err}`);
136       }
137     }
138     // Obtain the zoom ratio range supported by the camera.
139     let zoomRatioRange: Array<number> = [];
140     try {
141       zoomRatioRange = photoSession.getZoomRatioRange();
142     } catch (error) {
143       let err = error as BusinessError;
144       console.error(`Failed to get the zoom ratio range. error: ${err}`);
145     }
146     if (zoomRatioRange.length <= 0 ) {
147       return;
148     }
149     // Set a zoom ratio.
150     try {
151       photoSession.setZoomRatio(zoomRatioRange[0]);
152     } catch (error) {
153       let err = error as BusinessError;
154       console.error(`Failed to set the zoom ratio value. error: ${err}`);
155     }
156   }
157   ```
158
1595. Trigger photo capture.
160
161   Call [capture](../../reference/apis-camera-kit/arkts-apis-camera-PhotoOutput.md#capture-2) in the **PhotoOutput** class to capture a photo. In this API, the first parameter specifies the settings (for example, photo quality and rotation angle) for photo capture, and the second parameter is a callback function.
162
163   To obtain the photo rotation angle (specified by **rotation**), call [getPhotoRotation](../../reference/apis-camera-kit/arkts-apis-camera-PhotoOutput.md#getphotorotation12) in the [PhotoOutput](../../reference/apis-camera-kit/arkts-apis-camera-PhotoOutput.md) class.
164
165   ```ts
166   function capture(captureLocation: camera.Location, photoOutput: camera.PhotoOutput): void {
167     let settings: camera.PhotoCaptureSetting = {
168       quality: camera.QualityLevel.QUALITY_LEVEL_HIGH, // Set the photo quality to high.
169       rotation: camera.ImageRotation.ROTATION_0, // The photo rotation angle, camera.ImageRotation.ROTATION_0, is obtained through getPhotoRotation.
170       location: captureLocation, // Set the geolocation information of the photo.
171       mirror: false // Disable mirroring (disabled by default).
172     };
173     photoOutput.capture(settings, (err: BusinessError) => {
174       if (err) {
175         console.error(`Failed to capture the photo. error: ${err}`);
176         return;
177       }
178       console.info('Callback invoked to indicate the photo capture request success.');
179     });
180   }
181   ```
182
183## Status Listening
184
185During camera application development, you can listen for the status of the photo output stream, including the start of the photo stream, the start and end of the photo frame, and the errors of the photo output stream.
186
187- Register the **'captureStart'** event to listen for photo capture start events. This event can be registered when a PhotoOutput instance is created and is triggered when the camera device starts photo capture. The capture ID is returned.
188
189  ```ts
190  function onPhotoOutputCaptureStart(photoOutput: camera.PhotoOutput): void {
191    photoOutput.on('captureStartWithInfo', (err: BusinessError, captureStartInfo: camera.CaptureStartInfo) => {
192      if (err !== undefined && err.code !== 0) {
193        return;
194      }
195      console.info(`photo capture started, captureId : ${captureStartInfo.captureId}`);
196    });
197  }
198  ```
199
200- Register the **'captureEnd'** event to listen for photo capture end events. This event can be registered when a PhotoOutput instance is created and is triggered when the photo capture is complete. [CaptureEndInfo](../../reference/apis-camera-kit/arkts-apis-camera-i.md#captureendinfo) is returned.
201
202  ```ts
203  function onPhotoOutputCaptureEnd(photoOutput: camera.PhotoOutput): void {
204    photoOutput.on('captureEnd', (err: BusinessError, captureEndInfo: camera.CaptureEndInfo) => {
205      if (err !== undefined && err.code !== 0) {
206        return;
207      }
208      console.info(`photo capture end, captureId : ${captureEndInfo.captureId}`);
209      console.info(`frameCount : ${captureEndInfo.frameCount}`);
210    });
211  }
212  ```
213
214- Register the **'captureReady'** event to obtain the result of the next photo capture. This event can be registered when a PhotoOutput instance is created and is triggered when the camera device is ready for taking a photo. The information about the next photo capture is returned.
215
216  ```ts
217  function onPhotoOutputCaptureReady(photoOutput: camera.PhotoOutput): void {
218    photoOutput.on('captureReady', (err: BusinessError) => {
219      if (err !== undefined && err.code !== 0) {
220        return;
221      }
222      console.info(`photo capture ready`);
223    });
224  }
225  ```
226
227- Register the **'error'** event to listen for photo output errors. The callback function returns an error code when an API is incorrectly used. For details about the error code types, see [CameraErrorCode](../../reference/apis-camera-kit/arkts-apis-camera-e.md#cameraerrorcode).
228
229  ```ts
230  function onPhotoOutputError(photoOutput: camera.PhotoOutput): void {
231    photoOutput.on('error', (error: BusinessError) => {
232      console.error(`Photo output error code: ${error.code}`);
233    });
234  }
235  ```
236