• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Camera Photographing (ArkTS)
2
3Photographing 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.
4
5## How to Develop
6
7Read [Camera](../reference/apis-camera-kit/js-apis-camera.md) for the API reference.
8
91. Import the image module. The APIs provided by this module are used to obtain the surface ID and create a photo output stream.
10
11   ```ts
12   import image from '@ohos.multimedia.image';
13   import camera from '@ohos.multimedia.camera';
14   import fs from '@ohos.file.fs';
15   import PhotoAccessHelper from '@ohos.file.photoAccessHelper';
16   import { BusinessError } from '@ohos.base';
17   ```
18
192. Create a photo output stream.
20
21   Obtain the photo output streams supported by the current device from **photoProfiles** in the [CameraOutputCapability](../reference/apis-camera-kit/js-apis-camera.md#cameraoutputcapability) class, and then call [createPhotoOutput](../reference/apis-camera-kit/js-apis-camera.md#createphotooutput11) to pass in a supported output stream and the surface ID obtained in step 1 to create a photo output stream.
22
23   ```ts
24   function getPhotoOutput(cameraManager: camera.CameraManager, cameraOutputCapability: camera.CameraOutputCapability): camera.PhotoOutput | undefined {
25     let photoProfilesArray: Array<camera.Profile> = cameraOutputCapability.photoProfiles;
26     if (!photoProfilesArray) {
27       console.error("createOutput photoProfilesArray == null || undefined");
28     }
29     let photoOutput: camera.PhotoOutput | undefined = undefined;
30     try {
31       photoOutput = cameraManager.createPhotoOutput(photoProfilesArray[0]);
32     } catch (error) {
33       let err = error as BusinessError;
34       console.error(`Failed to createPhotoOutput. error: ${JSON.stringify(err)}`);
35     }
36     return photoOutput;
37   }
38   ```
39
403. Set the callback for the **photoAvailable** event and save the photo buffer as an image.
41
42    For details about how to obtain the context, see [Obtaining the Context of UIAbility](../application-models/uiability-usage.md#obtaining-the-context-of-uiability).
43
44   ```ts
45   let context = getContext(this);
46
47   async function savePicture(buffer: ArrayBuffer, img: image.Image) {
48     let photoAccessHelper: PhotoAccessHelper.PhotoAccessHelper = PhotoAccessHelper.getPhotoAccessHelper(context);
49     let options: PhotoAccessHelper.CreateOptions = {
50       title: Date.now().toString()
51     };
52     let photoUri: string = await photoAccessHelper.createAsset(PhotoAccessHelper.PhotoType.IMAGE, 'jpg', options);
53     // To call createAsset(), the application must have the ohos.permission.READ_IMAGEVIDEO and ohos.permission.WRITE_IMAGEVIDEO permissions.
54     let file: fs.File = fs.openSync(photoUri, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
55     await fs.write(file.fd, buffer);
56     fs.closeSync(file);
57     img.release();
58   }
59
60   function setPhotoOutputCb(photoOutput: camera.PhotoOutput) {
61   // After the callback is set, call capture() of photoOutput to transfer the photo buffer back to the callback.
62     photoOutput.on('photoAvailable', (errCode: BusinessError, photo: camera.Photo): void => {
63        console.info('getPhoto start');
64        console.info(`err: ${JSON.stringify(errCode)}`);
65        if (errCode || photo === undefined) {
66          console.error('getPhoto failed');
67          return;
68        }
69        let imageObj: image.Image = photo.main;
70        imageObj.getComponent(image.ComponentType.JPEG, (errCode: BusinessError, component: image.Component): void => {
71          console.info('getComponent start');
72          if (errCode || component === undefined) {
73            console.error('getComponent failed');
74            return;
75          }
76          let buffer: ArrayBuffer;
77          if (component.byteBuffer) {
78            buffer = component.byteBuffer;
79          } else {
80            console.error('byteBuffer is null');
81            return;
82          }
83          savePicture(buffer, imageObj);
84        });
85      });
86   }
87   ```
88
894. Set camera parameters.
90
91   You can set camera parameters to adjust photographing functions, including the flash, zoom ratio, and focal length.
92
93   ```ts
94   function configuringSession(photoSession: camera.PhotoSession): void {
95     // Check whether the camera has flash.
96     let flashStatus: boolean = false;
97     try {
98       flashStatus = photoSession.hasFlash();
99     } catch (error) {
100       let err = error as BusinessError;
101       console.error(`Failed to hasFlash. error: ${JSON.stringify(err)}`);
102     }
103     console.info(`Returned with the flash light support status: ${flashStatus}`);
104     if (flashStatus) {
105       // Check whether the auto flash mode is supported.
106       let flashModeStatus: boolean = false;
107       try {
108         let status: boolean = photoSession.isFlashModeSupported(camera.FlashMode.FLASH_MODE_AUTO);
109         flashModeStatus = status;
110       } catch (error) {
111         let err = error as BusinessError;
112         console.error(`Failed to check whether the flash mode is supported. error: ${JSON.stringify(err)}`);
113       }
114       if (flashModeStatus) {
115         // Set the flash mode to auto.
116         try {
117           photoSession.setFlashMode(camera.FlashMode.FLASH_MODE_AUTO);
118         } catch (error) {
119           let err = error as BusinessError;
120           console.error(`Failed to set the flash mode. error: ${JSON.stringify(err)}`);
121         }
122       }
123     }
124     // Check whether the continuous auto focus is supported.
125     let focusModeStatus: boolean = false;
126     try {
127       let status: boolean = photoSession.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO);
128       focusModeStatus = status;
129     } catch (error) {
130       let err = error as BusinessError;
131       console.error(`Failed to check whether the focus mode is supported. error: ${JSON.stringify(err)}`);
132     }
133     if (focusModeStatus) {
134       // Set the focus mode to continuous auto focus.
135       try {
136         photoSession.setFocusMode(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO);
137       } catch (error) {
138         let err = error as BusinessError;
139         console.error(`Failed to set the focus mode. error: ${JSON.stringify(err)}`);
140       }
141     }
142     // Obtain the zoom ratio range supported by the camera.
143     let zoomRatioRange: Array<number> = [];
144     try {
145       zoomRatioRange = photoSession.getZoomRatioRange();
146     } catch (error) {
147       let err = error as BusinessError;
148       console.error(`Failed to get the zoom ratio range. error: ${JSON.stringify(err)}`);
149     }
150     if (zoomRatioRange.length <= 0 ) {
151       return;
152     }
153     // Set a zoom ratio.
154     try {
155       photoSession.setZoomRatio(zoomRatioRange[0]);
156     } catch (error) {
157       let err = error as BusinessError;
158       console.error(`Failed to set the zoom ratio value. error: ${JSON.stringify(err)}`);
159     }
160   }
161   ```
162
1635. Trigger photographing.
164
165   Call [capture](../reference/apis-camera-kit/js-apis-camera.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 photographing, and the second parameter is a callback function.
166
167   ```ts
168   function capture(captureLocation: camera.Location, photoOutput: camera.PhotoOutput): void {
169     let settings: camera.PhotoCaptureSetting = {
170       quality: camera.QualityLevel.QUALITY_LEVEL_HIGH, // Set the photo quality to high.
171       rotation: camera.ImageRotation.ROTATION_0, // Set the rotation angle of the photo to 0.
172       location: captureLocation, // Set the geolocation information of the photo.
173       mirror: false // Disable mirroring (disabled by default).
174     };
175     photoOutput.capture(settings, (err: BusinessError) => {
176       if (err) {
177         console.error(`Failed to capture the photo. error: ${JSON.stringify(err)}`);
178         return;
179       }
180       console.info('Callback invoked to indicate the photo capture request success.');
181     });
182   }
183   ```
184
185## Status Listening
186
187During 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.
188
189- Register the **'captureStart'** event to listen for photographing start events. This event can be registered when a **PhotoOutput** instance is created and is triggered when the bottom layer starts exposure for photographing for the first time. The capture ID is returned.
190
191  ```ts
192  function onPhotoOutputCaptureStart(photoOutput: camera.PhotoOutput): void {
193    photoOutput.on('captureStartWithInfo', (err: BusinessError, captureStartInfo: camera.CaptureStartInfo) => {
194      console.info(`photo capture started, captureId : ${captureStartInfo.captureId}`);
195    });
196  }
197  ```
198
199- Register the **'captureEnd'** event to listen for photographing end events. This event can be registered when a **PhotoOutput** instance is created and is triggered when the photographing is complete. [CaptureEndInfo](../reference/apis-camera-kit/js-apis-camera.md#captureendinfo) is returned.
200
201  ```ts
202  function onPhotoOutputCaptureEnd(photoOutput: camera.PhotoOutput): void {
203    photoOutput.on('captureEnd', (err: BusinessError, captureEndInfo: camera.CaptureEndInfo) => {
204      console.info(`photo capture end, captureId : ${captureEndInfo.captureId}`);
205      console.info(`frameCount : ${captureEndInfo.frameCount}`);
206    });
207  }
208  ```
209
210- 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/js-apis-camera.md#cameraerrorcode).
211
212  ```ts
213  function onPhotoOutputError(photoOutput: camera.PhotoOutput): void {
214    photoOutput.on('error', (error: BusinessError) => {
215      console.error(`Photo output error code: ${error.code}`);
216    });
217  }
218  ```
219