• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Camera Preview (ArkTS)
2
3Preview is the image you see after you start the camera application but before you take photos or record videos.
4
5## How to Develop
6
7Read [Camera](../reference/apis-camera-kit/js-apis-camera.md) for the API reference.
8
91. Import the camera module, which provides camera-related attributes and methods.
10
11   ```ts
12   import camera from '@ohos.multimedia.camera';
13   import { BusinessError } from '@ohos.base';
14   ```
15
162. Create a surface.
17
18    The **\<XComponent>**, the capabilities of which are provided by the UI, offers the surface for preview streams. For details, see [XComponent](../reference/apis-arkui/arkui-ts/ts-basic-components-xcomponent.md).
19
20    > **NOTE**
21    >
22    > The preview stream and video output stream must have the same aspect ratio of the resolution. For example, the aspect ratio in the code snippet below is 1920:1080 (which is equal to 16:9), then the aspect ratio of the resolution of the preview stream must also be 16:9. This means that the resolution can be 640:360, 960:540, 1920:1080, or the like.
23
24   ```ets
25   // xxx.ets
26   // Create an XComponentController object.
27   @Component
28   struct XComponentPage {
29     // Create an XComponentController object.
30     mXComponentController: XComponentController = new XComponentController;
31     surfaceId: string = '';
32
33     build() {
34       Flex() {
35         // Create an XComponent object.
36         XComponent({
37           id: '',
38           type: 'surface',
39           libraryname: '',
40           controller: this.mXComponentController
41         })
42           .onLoad(() => {
43             // Set the surface width and height (1920 x 1080). For details about how to set the preview size, see the preview resolutions supported by the current device, which are obtained from previewProfilesArray.
44             // The preview stream and video output stream must have the same aspect ratio of the resolution.
45             this.mXComponentController.setXComponentSurfaceSize({surfaceWidth:1920,surfaceHeight:1080});
46             // Obtain the surface ID.
47             this.surfaceId = this.mXComponentController.getXComponentSurfaceId();
48           })
49           .width('1920px')
50           .height('1080px')
51       }
52     }
53   }
54   ```
55
563. Use **previewProfiles** in the [CameraOutputCapability](../reference/apis-camera-kit/js-apis-camera.md#cameraoutputcapability) class to obtain the preview output capabilities, in the format of an **previewProfilesArray** array, supported by the current device. Then call [createPreviewOutput](../reference/apis-camera-kit/js-apis-camera.md#createpreviewoutput) to create a **PreviewOutput** object, with the first parameter set to the first item in the **previewProfilesArray** array and the second parameter set to the surface ID obtained in step 2.
57
58   ```ts
59   function getPreviewOutput(cameraManager: camera.CameraManager, cameraOutputCapability: camera.CameraOutputCapability, surfaceId: string): camera.PreviewOutput | undefined {
60     let previewProfilesArray: Array<camera.Profile> = cameraOutputCapability.previewProfiles;
61     let previewOutput: camera.PreviewOutput | undefined = undefined;
62     try {
63       previewOutput = cameraManager.createPreviewOutput(previewProfilesArray[0], surfaceId);
64     } catch (error) {
65       let err = error as BusinessError;
66       console.error("Failed to create the PreviewOutput instance. error code: " + err.code);
67     }
68     return previewOutput;
69   }
70   ```
71
724. Call [Session.start](../reference/apis-camera-kit/js-apis-camera.md#start11) to start outputting the preview stream. If the call fails, an error code is returned. For details, see [CameraErrorCode](../reference/apis-camera-kit/js-apis-camera.md#cameraerrorcode).
73
74   ```ts
75   async function startPreviewOutput(cameraManager: camera.CameraManager, previewOutput: camera.PreviewOutput): Promise<void> {
76     let cameraArray: Array<camera.CameraDevice> = [];
77     cameraArray = cameraManager.getSupportedCameras();
78     if (cameraArray.length == 0) {
79       console.error('no camera.');
80       return;
81     }
82     // Obtain the supported modes.
83     let sceneModes: Array<camera.SceneMode> = cameraManager.getSupportedSceneModes(cameraArray[0]);
84     let isSupportPhotoMode: boolean = sceneModes.indexOf(camera.SceneMode.NORMAL_PHOTO) >= 0;
85     if (!isSupportPhotoMode) {
86       console.error('photo mode not support');
87       return;
88     }
89     let cameraInput: camera.CameraInput | undefined = undefined;
90     cameraInput = cameraManager.createCameraInput(cameraArray[0]);
91     if (cameraInput === undefined) {
92       console.error('cameraInput is undefined');
93       return;
94     }
95     // Open a camera.
96     await cameraInput.open();
97     let session: camera.PhotoSession = cameraManager.createSession(camera.SceneMode.NORMAL_PHOTO) as camera.PhotoSession;
98     session.beginConfig();
99     session.addInput(cameraInput);
100     session.addOutput(previewOutput);
101     await session.commitConfig();
102     await session.start();
103   }
104   ```
105
106
107## Status Listening
108
109During camera application development, you can listen for the preview output stream status, including preview stream start, preview stream end, and preview stream output errors.
110
111- Register the **'frameStart'** event to listen for preview start events. This event can be registered when a **PreviewOutput** object is created and is triggered when the bottom layer starts exposure for the first time. The preview stream starts as long as a result is returned.
112
113  ```ts
114  function onPreviewOutputFrameStart(previewOutput: camera.PreviewOutput): void {
115    previewOutput.on('frameStart', () => {
116      console.info('Preview frame started');
117    });
118  }
119  ```
120
121- Register the **'frameEnd'** event to listen for preview end events. This event can be registered when a **PreviewOutput** object is created and is triggered when the last frame of preview ends. The preview stream ends as long as a result is returned.
122
123  ```ts
124  function onPreviewOutputFrameEnd(previewOutput: camera.PreviewOutput): void {
125    previewOutput.on('frameEnd', () => {
126      console.info('Preview frame ended');
127    });
128  }
129  ```
130
131- Register the **'error'** event to listen for preview output errors. The callback function returns an error code when an API is incorrectly used. For details about the error code types, see [Camera Error Codes](../reference/apis-camera-kit/js-apis-camera.md#cameraerrorcode).
132
133  ```ts
134  function onPreviewOutputError(previewOutput: camera.PreviewOutput): void {
135    previewOutput.on('error', (previewOutputError: BusinessError) => {
136      console.error(`Preview output error code: ${previewOutputError.code}`);
137    });
138  }
139  ```
140