openharmony 鸿蒙 arkts-apis-camera-PreviewOutput

2026-08-25 浏览 (1)

Interface (PreviewOutput)

PreviewOutput implements preview output. It inherits from CameraOutput.

NOTE

The initial APIs of this module are supported since API version 10. Newly added APIs will be marked with a superscript to indicate their earliest API version.

Modules to Import

import { camera } from '@kit.CameraKit';

on('frameStart')

on(type: 'frameStart', callback: AsyncCallback<void>): void

Subscribes to preview frame start events. This API uses an asynchronous callback to return the result.

NOTE

Currently, you cannot use off() to unregister the callback in the callback method of on().

Atomic service API: This API can be used in atomic services since API version 19.

System capability: SystemCapability.Multimedia.Camera.Core

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value is fixed at 'frameStart'. The event can be listened for when a previewOutput instance is created. This event is triggered and returned when the bottom layer starts exposure for the first time.
callbackAsyncCallback<void>YesCallback used to return the result. The preview starts as long as this event is returned.

Example

import { BusinessError } from '@kit.BasicServicesKit';

function callback(err: BusinessError): void {
  if (err !== undefined && err.code !== 0) {
    console.error(`Callback Error, errorCode: ${err.code}`);
    return;
  }
  console.info('Preview frame started');
}

function registerPreviewOutputFrameStart(previewOutput: camera.PreviewOutput): void {
  previewOutput.on('frameStart', callback);
}

off('frameStart')

off(type: 'frameStart', callback?: AsyncCallback<void>): void

Unsubscribes from preview frame start events.

Atomic service API: This API can be used in atomic services since API version 19.

System capability: SystemCapability.Multimedia.Camera.Core

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value is fixed at 'frameStart'. The event can be listened for when a previewOutput instance is created.
callbackAsyncCallback<void>NoCallback used to return the result. If this parameter is specified, the subscription to the specified event with the specified callback is canceled. (The callback object cannot be an anonymous function.) Otherwise, the subscriptions to the specified event with all the callbacks are canceled.

Example

function unregisterPreviewOutputFrameStart(previewOutput: camera.PreviewOutput): void {
  previewOutput.off('frameStart');
}

on('frameEnd')

on(type: 'frameEnd', callback: AsyncCallback<void>): void

Subscribes to preview frame end events. This API uses an asynchronous callback to return the result.

NOTE

Currently, you cannot use off() to unregister the callback in the callback method of on().

Atomic service API: This API can be used in atomic services since API version 19.

System capability: SystemCapability.Multimedia.Camera.Core

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value is fixed at 'frameEnd'. The event can be listened for when a previewOutput instance is created. This event is triggered and returned when the last frame of preview ends.
callbackAsyncCallback<void>YesCallback used to return the result. The preview ends as long as this event is returned.

Example

import { BusinessError } from '@kit.BasicServicesKit';

function callback(err: BusinessError): void {
  if (err !== undefined && err.code !== 0) {
    console.error(`Callback Error, errorCode: ${err.code}`);
    return;
  }
  console.info('Preview frame ended');
}

function registerPreviewOutputFrameEnd(previewOutput: camera.PreviewOutput): void {
  previewOutput.on('frameEnd', callback);
}

off('frameEnd')

off(type: 'frameEnd', callback?: AsyncCallback<void>): void

Unsubscribes from preview frame end events.

Atomic service API: This API can be used in atomic services since API version 19.

System capability: SystemCapability.Multimedia.Camera.Core

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value is fixed at 'frameEnd'. The event can be listened for when a previewOutput instance is created.
callbackAsyncCallback<void>NoCallback used to return the result. If this parameter is specified, the subscription to the specified event with the specified callback is canceled. (The callback object cannot be an anonymous function.) Otherwise, the subscriptions to the specified event with all the callbacks are canceled.

Example

function unregisterPreviewOutputFrameEnd(previewOutput: camera.PreviewOutput): void {
  previewOutput.off('frameEnd');
}

on('error')

on(type: 'error', callback: ErrorCallback): void

Subscribes to PreviewOutput error events. This API uses an asynchronous callback to return the result.

NOTE

Currently, you cannot use off() to unregister the callback in the callback method of on().

Atomic service API: This API can be used in atomic services since API version 19.

System capability: SystemCapability.Multimedia.Camera.Core

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value is fixed at 'error'. The event can be listened for when a previewOutput instance is created. This event is triggered and the corresponding error message is returned when an error occurs during the use of a preview-related API such as Session.start or CameraOutput.release.
callbackErrorCallbackYesCallback used to return an error code defined in CameraErrorCode.

Example

import { BusinessError } from '@kit.BasicServicesKit';

function callback(previewOutputError: BusinessError): void {
  console.error(`Preview output error code: ${previewOutputError.code}`);
}

function registerPreviewOutputError(previewOutput: camera.PreviewOutput): void {
  previewOutput.on('error', callback)
}

off('error')

off(type: 'error', callback?: ErrorCallback): void

Unsubscribes from PreviewOutput error events.

Atomic service API: This API can be used in atomic services since API version 19.

System capability: SystemCapability.Multimedia.Camera.Core

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value is fixed at 'error'. The event can be listened for when a previewOutput instance is created.
callbackErrorCallbackNoCallback used to return the result. If this parameter is specified, the subscription to the specified event with the specified callback is canceled. (The callback object cannot be an anonymous function.) Otherwise, the subscriptions to the specified event with all the callbacks are canceled.

Example

function unregisterPreviewOutputError(previewOutput: camera.PreviewOutput): void {
  previewOutput.off('error');
}

getSupportedFrameRates12+

getSupportedFrameRates(): Array<FrameRateRange>

Obtains the supported frame rates.

Atomic service API: This API can be used in atomic services since API version 19.

System capability: SystemCapability.Multimedia.Camera.Core

Return value

TypeDescription
Array<FrameRateRange>Array of supported frame rates. If the API call fails, undefined is returned.

Example

function getSupportedFrameRates(previewOutput: camera.PreviewOutput): Array<camera.FrameRateRange> {
  let supportedFrameRatesArray: Array<camera.FrameRateRange> = previewOutput.getSupportedFrameRates();
  return supportedFrameRatesArray;
}

setFrameRate12+

setFrameRate(minFps: number, maxFps: number): void

Sets a frame rate range for preview streams. The range must be within the supported frame rate range,

which can be obtained by calling getSupportedFrameRates.

NOTE This API is valid only in PhotoSession or VideoSession mode.

Atomic service API: This API can be used in atomic services since API version 19.

System capability: SystemCapability.Multimedia.Camera.Core

Parameters

NameTypeMandatoryDescription
minFpsnumberYesMinimum frame rate, in fps. When the maximum value is less than the minimum value, the API does not take effect.
maxFpsnumberYesMaximum frame rate, in fps. When the minimum value is greater than the maximum value, the API does not take effect.

Error codes

For details about the error codes, see Camera Error Codes.

IDError Message
7400101Parameter missing or parameter type incorrect.
7400110Unresolved conflicts with current configurations.

Example

function setFrameRateRange(previewOutput: camera.PreviewOutput, frameRateRange: Array<number>): void {
  previewOutput.setFrameRate(frameRateRange[0], frameRateRange[1]);
}

getActiveFrameRate12+

getActiveFrameRate(): FrameRateRange

Obtains the configured frame rate range.

This API is valid only after setFrameRate is called to set a frame rate range for preview streams.

Atomic service API: This API can be used in atomic services since API version 19.

System capability: SystemCapability.Multimedia.Camera.Core

Return value

TypeDescription
FrameRateRangeFrame rate range.

Example

function getActiveFrameRate(previewOutput: camera.PreviewOutput): camera.FrameRateRange {
  let activeFrameRate: camera.FrameRateRange = previewOutput.getActiveFrameRate();
  return activeFrameRate;
}

getActiveProfile12+

getActiveProfile(): Profile

Obtains the profile that takes effect currently.

Atomic service API: This API can be used in atomic services since API version 19.

System capability: SystemCapability.Multimedia.Camera.Core

Return value

TypeDescription
ProfileProfile obtained.

Error codes

For details about the error codes, see Camera Error Codes.

IDError Message
7400201Camera service fatal error.

Example

import { BusinessError } from '@kit.BasicServicesKit';

function testGetActiveProfile(previewOutput: camera.PreviewOutput): camera.Profile|undefined {
  let activeProfile: camera.Profile|undefined = undefined;
  try {
    activeProfile = previewOutput.getActiveProfile();
  } catch (error) {
    // If the operation fails, error.code is returned and processed.
    let err = error as BusinessError;
    console.error(`The previewOutput.getActiveProfile call failed. error code: ${err.code}`);
  }
  return activeProfile;
}

getPreviewRotation12+

getPreviewRotation(displayRotation?: number): ImageRotation

Obtains the preview rotation angle.

  • Device' natural orientation: the default orientation for using a device. For example, the default orientation of the bar-type phone is in portrait mode, with the charging port facing downward.
  • Camera lens angle: equivalent to the angle at which the camera is rotated clockwise to match the device's natural orientation. For example, the rear camera sensor of a bar-type phone is installed in landscape mode. Therefore, it needs to be rotated by 90 degrees clockwise to match the device's natural orientation.
  • Screen rotation: indicates the clockwise rotation angle of the device screen.

Model restriction: This API can be used only in the stage model.

Atomic service API: This API can be used in atomic services since API version 19.

System capability: SystemCapability.Multimedia.Camera.Core

Parameters

NameTypeMandatoryDescription
displayRotationnumberNoScreen rotation angle of the display. It is obtained by calling display.getDefaultDisplaySync.
Since API version 23, the input parameter displayRotation is optional. If no parameter is passed, the system obtains the displayRotation value to calculate rotation angle of a video.

Return value

TypeDescription
ImageRotationThe preview rotation angle obtained. If the API call fails, undefined is returned.

Error codes

For details about the error codes, see Camera Error Codes.

IDError Message
7400201Camera service fatal error.

Example

import { BusinessError } from '@kit.BasicServicesKit';

function testGetPreviewRotation(previewOutput: camera.PreviewOutput, imageRotation : camera.ImageRotation): camera.ImageRotation {
  let previewRotation: camera.ImageRotation = camera.ImageRotation.ROTATION_0;
  try {
    previewRotation = previewOutput.getPreviewRotation(imageRotation);
    console.info(`Preview rotation is: ${previewRotation}`);
  } catch (error) {
    // If the operation fails, error.code is returned and processed.
    let err = error as BusinessError;
    console.error(`The previewOutput.getPreviewRotation call failed. error code: ${err.code}`);
  }
  return previewRotation;
}

function testGetPreviewRotationWithOutParam(previewOutput: camera.PreviewOutput): camera.ImageRotation {
  let previewRotation: camera.ImageRotation = camera.ImageRotation.ROTATION_0;
  try {
    previewRotation = previewOutput.getPreviewRotation();
    console.info(`Preview rotation is: ${previewRotation}`);
  } catch (error) {
    // If the operation fails, error.code is returned and processed.
    let err = error as BusinessError;
    console.error(`The previewOutput.testGetPreviewRotationWithOutParam call failed. error code: ${err.code}`);
  }
  return previewRotation;
}

setPreviewRotation12+

setPreviewRotation(previewRotation: ImageRotation, isDisplayLocked?: boolean): void

Sets the preview rotation angle.

Atomic service API: This API can be used in atomic services since API version 19.

System capability: SystemCapability.Multimedia.Camera.Core

Parameters

NameTypeMandatoryDescription
previewRotationImageRotationYesPreview rotation angle.
isDisplayLockedbooleanNoWhether the orientation of the surface is locked when the screen rotates. If this parameter is not set, the default value false is used, indicating that the orientation is not locked. true if locked, false otherwise. For details, see SurfaceRotationOptions.

Error codes

For details about the error codes, see Camera Error Codes.

IDError Message
7400101Parameter missing or parameter type incorrect.
7400201Camera service fatal error.

Example

import { BusinessError } from '@kit.BasicServicesKit';

function testSetPreviewRotation(previewOutput: camera.PreviewOutput, previewRotation : camera.ImageRotation, isDisplayLocked: boolean): void {
  try {
    previewOutput.setPreviewRotation(previewRotation, isDisplayLocked);
  } catch (error) {
    // If the operation fails, error.code is returned and processed.
    let err = error as BusinessError;
    console.error(`The previewOutput.setPreviewRotation call failed. error code: ${err.code}`);
  }
  return;
}

start(deprecated)

start(callback: AsyncCallback<void>): void

Starts to output preview streams. This API uses an asynchronous callback to return the result.

NOTE This API is supported since API version 10 and deprecated since API version 11. You are advised to use Session.start instead.

System capability: SystemCapability.Multimedia.Camera.Core

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<void>YesCallback used to return the result. If the preview stream output starts successfully, err is undefined; otherwise, err is an error object with an error code defined in CameraErrorCode.

Error codes

For details about the error codes, see Camera Error Codes.

IDError Message
7400103Session not config.

Example

import { BusinessError } from '@kit.BasicServicesKit';

function startPreviewOutput(previewOutput: camera.PreviewOutput): void {
  previewOutput.start((err: BusinessError) => {
    if (err) {
      console.error(`Failed to start the preview output, error code: ${err.code}.`);
      return;
    }
    console.info('Callback returned with preview output started.');
  });
}

start(deprecated)

start(): Promise<void>

Starts to output preview streams. This API uses a promise to return the result.

NOTE This API is supported since API version 10 and deprecated since API version 11. You are advised to use Session.start instead.

System capability: SystemCapability.Multimedia.Camera.Core

Return value

TypeDescription
Promise<void>Promise that returns no value.

Error codes

For details about the error codes, see Camera Error Codes.

IDError Message
7400103Session not config.

Example

import { BusinessError } from '@kit.BasicServicesKit';

function startPreviewOutput(previewOutput: camera.PreviewOutput): void {
  previewOutput.start().then(() => {
    console.info('Promise returned with preview output started.');
  }).catch((error: BusinessError) => {
    console.error(`Failed to preview output start, error code: ${error.code}.`);
  });
}

stop(deprecated)

stop(callback: AsyncCallback<void>): void

Stops outputting preview streams. This API uses an asynchronous callback to return the result.

NOTE This API is supported since API version 10 and deprecated since API version 11. You are advised to use Session.stop instead.

System capability: SystemCapability.Multimedia.Camera.Core

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<void>YesCallback used to return the result. If the preview stream output stops successfully, err is undefined; otherwise, err is an error object.

Example

import { BusinessError } from '@kit.BasicServicesKit';

function stopPreviewOutput(previewOutput: camera.PreviewOutput): void {
  previewOutput.stop((err: BusinessError) => {
    if (err) {
      console.error(`Failed to stop the preview output, error code: ${err.code}.`);
      return;
    }
    console.info('Returned with preview output stopped.');
  })
}

stop(deprecated)

stop(): Promise<void>

Stops outputting preview streams. This API uses a promise to return the result.

NOTE This API is supported since API version 10 and deprecated since API version 11. You are advised to use Session.stop instead.

System capability: SystemCapability.Multimedia.Camera.Core

Return value

TypeDescription
Promise<void>Promise that returns no value.

Example

import { BusinessError } from '@kit.BasicServicesKit';

function stopPreviewOutput(previewOutput: camera.PreviewOutput): void {
  previewOutput.stop().then(() => {
    console.info('Callback returned with preview output stopped.');
  }).catch((error: BusinessError) => {
    console.error(`Failed to preview output stop, error code: ${error.code}.`);
  });
}

isBandwidthCompressionSupported23+

isBandwidthCompressionSupported(): boolean

Checks whether preview bandwidth compression is supported. This involves reducing data volume through encoding to minimize bandwidth usage during transmission.

Atomic service API: This API can be used in atomic services since API version 23.

System capability: SystemCapability.Multimedia.Camera.Core

Return value

TypeDescription
booleanCheck result for the support of preview bandwidth compression. true if supported, false otherwise.

Example

import { BusinessError } from '@kit.BasicServicesKit';

function isBandwidthCompressionSupported(previewOutput: camera.PreviewOutput): boolean {
  let supported: boolean = false;
  try {
    supported = previewOutput.isBandwidthCompressionSupported();
  } catch (error) {
    // If the operation fails, error.code is returned and processed.
    let err = error as BusinessError;
    console.error(`The previewOutput.isBandwidthCompressionSupported call failed. error code: ${err.code}`);
  }
  return supported;
}

enableBandwidthCompression23+

enableBandwidthCompression(enabled: boolean): void

Enables preview bandwidth compression.

Before enabling this feature, you can call isBandwidthCompressionSupported to check whether the device supports preview bandwidth compression.

NOTE This function must be called prior to Session.commitConfig. Otherwise, the preview output stream format will be affected.

Atomic service API: This API can be used in atomic services since API version 23.

System capability: SystemCapability.Multimedia.Camera.Core

Parameters

NameTypeMandatoryDescription
enabledbooleanYesWhether to enable preview bandwidth compression. true to enable, false otherwise.

Error codes

For details about the error codes, see Camera Error Codes.

IDError Message
7400102Operation not allowed.
7400103Session not config.
7400201Camera service fatal error.

Example

import { BusinessError } from '@kit.BasicServicesKit';

function enableBandwidthCompression(previewOutput: camera.PreviewOutput, enabled: boolean): void {
  try {
    previewOutput.enableBandwidthCompression(enabled);
  } catch (error) {
    // If the operation fails, error.code is returned and processed.
    let err = error as BusinessError;
    console.error(`The previewOutput.enableBandwidthCompression call failed. error code: ${err.code}`);
  }
}

addDeferredSurface24+

addDeferredSurface(surfaceId: string): void

Adds a surface for delayed preview. This API can run after Session.commitConfig or Session.start is called.

Atomic service API: This API can be used in atomic services since API version 24.

System capability: SystemCapability.Multimedia.Camera.Core

Parameters

NameTypeMandatoryDescription
surfaceIdstringYesSurface ID, which is obtained from XComponent.

Error codes

For details about the error codes, see Camera Error Codes.

IDError Message
7400101Parameter missing or parameter type incorrect.

Example

import { BusinessError } from '@kit.BasicServicesKit';

async function preview(cameraManager: camera.CameraManager, cameraInfo: camera.CameraDevice, previewProfile: camera.Profile, photoProfile: camera.Profile, mode: camera.SceneMode, previewSurfaceId: string): Promise<void> {
  let cameraInput: camera.CameraInput = cameraManager.createCameraInput(cameraInfo);
  let previewOutput: camera.PreviewOutput = cameraManager.createDeferredPreviewOutput(previewProfile);
  let photoOutput: camera.PhotoOutput = cameraManager.createPhotoOutput(photoProfile);
  let session: camera.Session  = cameraManager.createSession(mode);
  session.beginConfig();
  session.addInput(cameraInput);
  session.addOutput(previewOutput);
  session.addOutput(photoOutput);
  await session.commitConfig();
  try {
    await session.start();
  } catch (error) {
    // If the operation fails, error.code is returned and processed.
    let err = error as BusinessError;
    console.error(`start session failed. error code: ${err.code}`);
  }
  previewOutput.addDeferredSurface(previewSurfaceId);
}

你可能感兴趣的鸿蒙文章

openharmony 鸿蒙 capi-oh-camera-capturesession-callbacks

openharmony 鸿蒙 arkts-apis-camera-OIS

openharmony 鸿蒙 capi-oh-camera-camera-devicequeryinfo

openharmony 鸿蒙 capi-oh-camera-camera-frameraterange

openharmony 鸿蒙 capi-oh-camera-camera-outputcapability

openharmony 鸿蒙 arkts-apis-camera-Photo

openharmony 鸿蒙 capi-oh-camera-camera-profile

openharmony 鸿蒙 capi-oh-camera-camera-manager

openharmony 鸿蒙 capi-oh-camera-previewoutput-callbacks

openharmony 鸿蒙 arkts-apis-camera-ManualExposureQuery

  • 所属分类: 后端技术
  • 本文标签: 软件 鸿蒙
  • 版权声明: 本文链接 https://seaxiang.com/blog/mRuRcrVG