• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Camera Photographing Sample
2
3## Development Process
4
5After obtaining the output stream capabilities supported by the camera, create a photo stream. The development process is as follows:
6
7![Photographing Development Process](figures/photographing-development-process.png)
8
9## Sample Code
10
11```ts
12import camera from '@ohos.multimedia.camera'
13import image from '@ohos.multimedia.image'
14import media from '@ohos.multimedia.media'
15
16// Create a CameraManager instance.
17context: any = getContext(this)
18let cameraManager = camera.getCameraManager(this.context)
19if (!cameraManager) {
20    console.error("camera.getCameraManager error")
21    return;
22}
23// Listen for camera status changes.
24cameraManager.on('cameraStatus', (cameraStatusInfo) => {
25    console.info(`camera : ${cameraStatusInfo.camera.cameraId}`);
26    console.info(`status: ${cameraStatusInfo.status}`);
27})
28
29// Obtain the camera list.
30let cameraArray = cameraManager.getSupportedCameras();
31if (cameraArray.length <= 0) {
32    console.error("cameraManager.getSupportedCameras error")
33    return;
34}
35
36for (let index = 0; index < cameraArray.length; index++) {
37    console.info('cameraId : ' + cameraArray[index].cameraId);                          // Obtain the camera ID.
38    console.info('cameraPosition : ' + cameraArray[index].cameraPosition);              // Obtain the camera position.
39    console.info('cameraType : ' + cameraArray[index].cameraType);                      // Obtain the camera type.
40    console.info('connectionType : ' + cameraArray[index].connectionType);              // Obtain the camera connection type.
41}
42
43// Create a camera input stream.
44let cameraInput
45try {
46    cameraInput = cameraManager.createCameraInput(cameraArray[0]);
47} catch (error) {
48   console.error('Failed to createCameraInput errorCode = ' + error.code);
49}
50
51// Listen for camera input errors.
52let cameraDevice = cameraArray[0];
53cameraInput.on('error', cameraDevice, (error) => {
54    console.info(`Camera input error code: ${error.code}`);
55})
56
57// Open the camera.
58await cameraInput.open();
59
60// Obtain the output stream capabilities supported by the camera.
61let cameraOutputCap = cameraManager.getSupportedOutputCapability(cameraArray[0]);
62if (!cameraOutputCap) {
63    console.error("cameraManager.getSupportedOutputCapability error")
64    return;
65}
66console.info("outputCapability: " + JSON.stringify(cameraOutputCap));
67
68let previewProfilesArray = cameraOutputCap.previewProfiles;
69if (!previewProfilesArray) {
70    console.error("createOutput previewProfilesArray == null || undefined")
71}
72
73let photoProfilesArray = cameraOutputCap.photoProfiles;
74if (!photoProfilesArray) {
75    console.error("createOutput photoProfilesArray == null || undefined")
76}
77
78// Create a preview output stream. For details about the surfaceId parameter, see the XComponent. The preview stream is the surface provided by the XComponent.
79let previewOutput
80try {
81    previewOutput = cameraManager.createPreviewOutput(previewProfilesArray[0], surfaceId)
82} catch (error) {
83    console.error("Failed to create the PreviewOutput instance.")
84}
85
86// Listen for preview output errors.
87previewOutput.on('error', (error) => {
88    console.info(`Preview output error code: ${error.code}`);
89})
90
91// Create an ImageReceiver instance and set photographing parameters. Wherein, the resolution must be one of the photographing resolutions supported by the current device, which are obtained by photoProfilesArray.
92let imageReceiver = await image.createImageReceiver(1920, 1080, 4, 8)
93// Obtain the surface ID for displaying the photos.
94let photoSurfaceId = await imageReceiver.getReceivingSurfaceId()
95// Create a photo output stream.
96let photoOutput
97try {
98    photoOutput = cameraManager.createPhotoOutput(photoProfilesArray[0], photoSurfaceId)
99} catch (error) {
100   console.error('Failed to createPhotoOutput errorCode = ' + error.code);
101}
102// Create a session.
103let captureSession
104try {
105    captureSession = cameraManager.createCaptureSession()
106} catch (error) {
107    console.error('Failed to create the CaptureSession instance. errorCode = ' + error.code);
108}
109
110// Listen for session errors.
111captureSession.on('error', (error) => {
112    console.info(`Capture session error code: ${error.code}`);
113})
114
115// Start configuration for the session.
116try {
117    captureSession.beginConfig()
118} catch (error) {
119    console.error('Failed to beginConfig. errorCode = ' + error.code);
120}
121
122// Add the camera input stream to the session.
123try {
124    captureSession.addInput(cameraInput)
125} catch (error) {
126    console.error('Failed to addInput. errorCode = ' + error.code);
127}
128
129// Add the preview output stream to the session.
130try {
131    captureSession.addOutput(previewOutput)
132} catch (error) {
133    console.error('Failed to addOutput(previewOutput). errorCode = ' + error.code);
134}
135
136// Add the photo output stream to the session.
137try {
138    captureSession.addOutput(photoOutput)
139} catch (error) {
140    console.error('Failed to addOutput(photoOutput). errorCode = ' + error.code);
141}
142
143// Commit the session configuration.
144await captureSession.commitConfig()
145
146// Start the session.
147await captureSession.start().then(() => {
148    console.info('Promise returned to indicate the session start success.');
149})
150// Check whether the camera has flash.
151let flashStatus
152try {
153    flashStatus = captureSession.hasFlash()
154} catch (error) {
155    console.error('Failed to hasFlash. errorCode = ' + error.code);
156}
157console.info('Promise returned with the flash light support status:' + flashStatus);
158
159if (flashStatus) {
160    // Check whether the auto flash mode is supported.
161    let flashModeStatus
162    try {
163        let status = captureSession.isFlashModeSupported(camera.FlashMode.FLASH_MODE_AUTO)
164        flashModeStatus = status
165    } catch (error) {
166        console.error('Failed to check whether the flash mode is supported. errorCode = ' + error.code);
167    }
168    if(flashModeStatus) {
169        // Set the flash mode to auto.
170        try {
171            captureSession.setFlashMode(camera.FlashMode.FLASH_MODE_AUTO)
172        } catch (error) {
173            console.error('Failed to set the flash mode. errorCode = ' + error.code);
174        }
175    }
176}
177
178// Check whether the continuous auto focus is supported.
179let focusModeStatus
180try {
181    let status = captureSession.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO)
182    focusModeStatus = status
183} catch (error) {
184    console.error('Failed to check whether the focus mode is supported. errorCode = ' + error.code);
185}
186
187if (focusModeStatus) {
188    // Set the focus mode to continuous auto focus.
189    try {
190        captureSession.setFocusMode(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO)
191    } catch (error) {
192        console.error('Failed to set the focus mode. errorCode = ' + error.code);
193    }
194}
195
196// Obtain the zoom ratio range supported by the camera.
197let zoomRatioRange
198try {
199    zoomRatioRange = captureSession.getZoomRatioRange()
200} catch (error) {
201    console.error('Failed to get the zoom ratio range. errorCode = ' + error.code);
202}
203
204// Set a zoom ratio.
205try {
206    captureSession.setZoomRatio(zoomRatioRange[0])
207} catch (error) {
208    console.error('Failed to set the zoom ratio value. errorCode = ' + error.code);
209}
210let settings = {
211    quality: camera.QualityLevel.QUALITY_LEVEL_HIGH,                                     // Set the photo quality to high.
212    rotation: camera.ImageRotation.ROTATION_0                                            // Set the rotation angle of the photo to 0.
213}
214// Use the current photographing settings to take photos.
215photoOutput.capture(settings, async (err) => {
216    if (err) {
217        console.error('Failed to capture the photo ${err.message}');
218        return;
219    }
220    console.info('Callback invoked to indicate the photo capture request success.');
221});
222// Stop the session.
223captureSession.stop()
224
225// Release the camera input stream.
226cameraInput.close()
227
228// Release the preview output stream.
229previewOutput.release()
230
231// Release the photo output stream.
232photoOutput.release()
233
234// Release the session.
235captureSession.release()
236
237// Set the session to null.
238captureSession = null
239```
240