1# Preview (ArkTS)
2
3Before developing a camera application, request permissions by following the instructions provided in [Camera Development Preparations](camera-preparation.md).
4
5Preview is the image you see after you start the camera application but before you take photos or record videos.
6
7## How to Develop
8
9Read [Camera](../../reference/apis-camera-kit/js-apis-camera.md) for the API reference.
10
111. Import the camera module, which provides camera-related attributes and methods.
12
13   ```ts
14   import { camera } from '@kit.CameraKit';
15   import { BusinessError } from '@kit.BasicServicesKit';
16   ```
17
182. Create a surface.
19
20    The **XComponent**, the capabilities of which are provided by the UI, offers the surface for preview streams. For details about how to obtain the surface ID, see [getXcomponentSurfaceId](../../reference/apis-arkui/arkui-ts/ts-basic-components-xcomponent.md#getxcomponentsurfaceid9). For details about the component, see [XComponent](../../reference/apis-arkui/arkui-ts/ts-basic-components-xcomponent.md).
21
22    > **NOTE**
23    >
24    > The preview stream and video output stream must have the same aspect ratio of the resolution. For example, the aspect ratio of the surface of the **XComponent** 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.
25
263. 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.
27
28   ```ts
29   function getPreviewOutput(cameraManager: camera.CameraManager, cameraOutputCapability: camera.CameraOutputCapability, surfaceId: string): camera.PreviewOutput | undefined {
30     let previewProfilesArray: Array<camera.Profile> = cameraOutputCapability.previewProfiles;
31     let previewOutput: camera.PreviewOutput | undefined = undefined;
32     try {
33       previewOutput = cameraManager.createPreviewOutput(previewProfilesArray[0], surfaceId);
34     } catch (error) {
35       let err = error as BusinessError;
36       console.error("Failed to create the PreviewOutput instance. error code: " + err.code);
37     }
38     return previewOutput;
39   }
40   ```
41
424. 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).
43
44   ```ts
45   async function startPreviewOutput(cameraManager: camera.CameraManager, previewOutput: camera.PreviewOutput): Promise<void> {
46     let cameraArray: Array<camera.CameraDevice> = [];
47     cameraArray = cameraManager.getSupportedCameras();
48     if (cameraArray.length == 0) {
49       console.error('no camera.');
50       return;
51     }
52     // Obtain the supported modes.
53     let sceneModes: Array<camera.SceneMode> = cameraManager.getSupportedSceneModes(cameraArray[0]);
54     let isSupportPhotoMode: boolean = sceneModes.indexOf(camera.SceneMode.NORMAL_PHOTO) >= 0;
55     if (!isSupportPhotoMode) {
56       console.error('photo mode not support');
57       return;
58     }
59     let cameraInput: camera.CameraInput | undefined = undefined;
60     cameraInput = cameraManager.createCameraInput(cameraArray[0]);
61     if (cameraInput === undefined) {
62       console.error('cameraInput is undefined');
63       return;
64     }
65     // Open a camera.
66     await cameraInput.open();
67     let session: camera.PhotoSession = cameraManager.createSession(camera.SceneMode.NORMAL_PHOTO) as camera.PhotoSession;
68     session.beginConfig();
69     session.addInput(cameraInput);
70     session.addOutput(previewOutput);
71     await session.commitConfig();
72     await session.start();
73   }
74   ```
75
76
77## Status Listening
78
79During camera application development, you can listen for the preview output stream status, including preview stream start, preview stream end, and preview stream output errors.
80
81- 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.
82
83  ```ts
84  function onPreviewOutputFrameStart(previewOutput: camera.PreviewOutput): void {
85    previewOutput.on('frameStart', (err: BusinessError) => {
86      if (err !== undefined && err.code !== 0) {
87        return;
88      }
89      console.info('Preview frame started');
90    });
91  }
92  ```
93
94- 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.
95
96  ```ts
97  function onPreviewOutputFrameEnd(previewOutput: camera.PreviewOutput): void {
98    previewOutput.on('frameEnd', (err: BusinessError) => {
99      if (err !== undefined && err.code !== 0) {
100        return;
101      }
102      console.info('Preview frame ended');
103    });
104  }
105  ```
106
107- 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 [CameraErrorCode](../../reference/apis-camera-kit/js-apis-camera.md#cameraerrorcode).
108
109  ```ts
110  function onPreviewOutputError(previewOutput: camera.PreviewOutput): void {
111    previewOutput.on('error', (previewOutputError: BusinessError) => {
112      console.error(`Preview output error code: ${previewOutputError.code}`);
113    });
114  }
115  ```
116