目录

Adjusting Camera Rotation Angles (ArkTS)

Depending on the screen orientation, the captured image may need to be rotated to ensure it appears in the correct direction on the screen, as illustrated in the figure below.

This topic describes how to adjust the camera's rotation angle in preview, photo capture, and video recording scenarios.

This development guide provides two solutions for obtaining the rotation angles for preview, photographing, and video recording:

For details about the APIs, see Camera API Reference.

Creating a Session

  1. Import the camera module and other related modules.

    import { camera } from '@kit.CameraKit';
    import { BusinessError } from '@kit.BasicServicesKit';
  2. Create a session.

    Before using functions such as preview, you need to create a camera session. Call the createSession API in CameraManager to create a session. When creating a session, set SceneMode to NORMAL_PHOTO or NORMAL_VIDEO. The created session is in photographing or video recording mode.

    createPhotoSession(cameraManager: camera.CameraManager): camera.Session | undefined {
      let session: camera.Session | undefined = undefined;
      try {
        session = cameraManager.createSession(camera.SceneMode.NORMAL_PHOTO) as camera.PhotoSession;
      } catch (error) {
        let err = error as BusinessError;
        console.error(`Failed to create the session instance. error: ${err}`);
      }
      return session;
    }
    
    createVideoSession(cameraManager: camera.CameraManager): camera.Session | undefined {
      let session: camera.Session | undefined = undefined;
      try {
        session = cameraManager.createSession(camera.SceneMode.NORMAL_VIDEO) as camera.VideoSession;
      } catch (error) {
        let err = error as BusinessError;
        console.error(`Failed to create the session instance. error: ${err}`);
      }
      return session;
    }

Preview

After the session is created, you can configure output streams as required.

  1. Obtain and set the preview rotation angle during session configuration. That is, call this API after submitting related configurations using the commitConfig API. You are advised to call this API before starting streams in Start.

    API Description Solution
    • Solution 1:

      The application obtains the Display object through the display.getDefaultDisplaySync API and reads the value of the rotation attribute to calculate displayRotation (indicating the screen rotation angle of the display device), and fills the corresponding angle in the getPreviewRotation API.

      For example, if Display.rotation is set to 1, the display device's screen is rotated clockwise by 90°. In this case, set displayRotation to 90.

      • The isDisplayLocked parameter is optional. The default value is false. If this parameter is set to false, the screen orientation is not locked, and the preview rotation angle is calculated based on the sum of the camera lens installation angle and screen rotation angle. If this parameter is set to true, the surface rotation is locked and does not change with the window movements, and the preview rotation angle is calculated only based on the camera lens installation angle.
      import { display } from '@kit.ArkUI';
      import { camera } from '@kit.CameraKit';
      
      GetAndSetPreviewRotation(previewOutput: camera.PreviewOutput) {
        // previewOutput is the created preview output.
        try {
          let displayRotation = display.getDefaultDisplaySync().rotation;
          let previewRotation = previewOutput.getPreviewRotation(displayRotation * camera.ImageRotation.ROTATION_90);
          let isDisplayLocked: boolean = false; // It is recommended that the value be the same as the lock attribute of the input parameter setXComponentSurfaceRotation.
          previewOutput.setPreviewRotation(previewRotation, isDisplayLocked);
        } catch (error) {
          // If the operation fails, error.code is returned and processed.
          let err = error as BusinessError;
          console.error(`GetAndSetPreviewRotation call failed. error code: ${err.code}`);
        }
      }
    • Solution 2

      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. If the application uses a USB camera or in multi-screen scenarios, solution 2 is recommended.

      • The isDisplayLocked parameter is optional. The default value is false. If this parameter is set to false, the screen orientation is not locked, and the preview rotation angle is calculated based on the sum of the camera lens installation angle and screen rotation angle. If this parameter is set to true, the surface rotation is locked and does not change with the window movements, and the preview rotation angle is calculated only based on the camera lens installation angle.
      import { camera } from '@kit.CameraKit';
      
      GetAndSetPreviewRotationWithoutDisplayRotation(previewOutput: camera.PreviewOutput) {
        // previewOutput is the created preview output.
        try {
          let previewRotation = previewOutput.getPreviewRotation();
          let isDisplayLocked: boolean = false; // It is recommended that the value be the same as the lock attribute of the input parameter setXComponentSurfaceRotation.
          previewOutput.setPreviewRotation(previewRotation, isDisplayLocked);
        } catch (error) {
          // If the operation fails, error.code is returned and processed.
          let err = error as BusinessError;
          console.error(`GetAndSetPreviewRotationWithoutDisplayRotation call failed. error code: ${err.code}`);
        }
      }
  2. Listen to the display object changes to detect the current status of the window. For example, when the current camera window rotates, the angle of the preview stream needs to be corrected. You are advised to create a listener after obtaining and setting the preview stream rotation in the session configuration.

    • Solution 1:

      display.off('change');
      display.on('change', () => {
        GetAndSetPreviewRotation(previewOutput);
      });
    • Solution 2

      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. If the application uses a USB camera or in multi-screen scenarios, solution 2 is recommended.

      display.off('change');
      display.on('change', () => {
        GetAndSetPreviewRotationWithoutDisplayRotation(previewOutput);
      });

Photographing

After the session is created, you can configure output streams as required.

  1. Call getPhotoRotation in PhotoOutput to obtain the rotation angle. This API needs to be called after the session calls commitConfig to complete stream configuration.

    • Solution 1:

      In the API, the deviceDegree parameter specifies the device rotation angle. The photo rotation angle is related to the gravity direction (that is, rotation angle of the device). For details about how to obtain the value, see Calculating the Device Rotation Angle.

      getPhotoRotation(photoOutput: camera.PhotoOutput, deviceDegree: number): camera.ImageRotation {
        let photoRotation: camera.ImageRotation = camera.ImageRotation.ROTATION_0;
        try {
          photoRotation = photoOutput.getPhotoRotation(deviceDegree);
          console.info(`Photo rotation is: ${photoRotation}`);
        } catch (error) {
          // If the operation fails, error.code is returned and processed.
          let err = error as BusinessError;
          console.error(`The photoOutput.getPhotoRotation call failed. error code: ${err.code}`);
        }
        return photoRotation;
      }
    • Solution 2

      Since API version 23, the input parameter deviceDegree is optional. If no parameter is passed, the system obtains the deviceDegree value to calculate the photo rotation angle. If the gravity sensor data is invalid and deviceDegree cannot be calculated, the system uses the last valid deviceDegree. If the application uses a USB camera or in multi-screen scenarios, solution 2 is recommended.

      getPhotoRotationWithoutDeviceDegree(photoOutput: camera.PhotoOutput): camera.ImageRotation {
        let photoRotation: camera.ImageRotation = camera.ImageRotation.ROTATION_0;
        try {
          photoRotation = photoOutput.getPhotoRotation();
          console.info(`Photo rotation is: ${photoRotation}`);
        } catch (error) {
          // If the operation fails, error.code is returned and processed.
          let err = error as BusinessError;
          console.error(`The photoOutput.getPhotoRotationWithoutDeviceDegree call failed. error code: ${err.code}`);
        }
        return photoRotation;
      }
  2. Write the photographing angle to PhotoCaptureSetting.rotation.

  3. Follow the instructions provided in Photo Capture (ArkTS) to configure other parameters and start photo capture.

Video Recording

After the session is created, you can configure output streams as required.

  1. You can call getVideoRotation in VideoOutput to obtain the rotation angle of the recording. This API needs to be called after the session calls commitConfig to complete stream configuration.

    • Solution 1:

      In the API, the deviceDegree parameter specifies the device rotation angle. The video rotation angle is related to the gravity direction (that is, rotation angle of the device). For details about how to obtain the value, see Calculating the Device Rotation Angle.

      getVideoRotation(videoOutput: camera.VideoOutput, deviceDegree: number): camera.ImageRotation {
        let videoRotation: camera.ImageRotation = camera.ImageRotation.ROTATION_0;
        try {
          videoRotation = videoOutput.getVideoRotation(deviceDegree);
          console.info(`Video rotation is: ${videoRotation}`);
        } catch (error) {
          // If the operation fails, error.code is returned and processed.
          let err = error as BusinessError;
          console.error(`The videoOutput.getVideoRotation call failed. error code: ${err.code}`);
        }
        return videoRotation;
      }
    • Solution 2

      Since API version 23, the input parameter deviceDegree is optional. If no parameter is passed, the system obtains the deviceDegree value to calculate the video rotation angle. If the gravity sensor data is invalid and deviceDegree cannot be calculated, the system uses the last valid deviceDegree. If the application uses a USB camera or in multi-screen scenarios, solution 2 is recommended.

      getVideoRotationWithoutDeviceDegree(videoOutput: camera.VideoOutput): camera.ImageRotation {
        let videoRotation: camera.ImageRotation = camera.ImageRotation.ROTATION_0;
        try {
          videoRotation = videoOutput.getVideoRotation();
          console.info(`Video rotation is: ${videoRotation}`);
        } catch (error) {
          // If the operation fails, error.code is returned and processed.
          let err = error as BusinessError;
          console.error(`The videoOutput.getVideoRotationWithoutDeviceDegree call failed. error code: ${err.code}`);
        }
        return videoRotation;
      }
  2. Call updateRotation following AVRecorder.prepare to set the recording angle.

  3. Follow the instructions provided in Video Recording (ArkTS) to configure other parameters and start video recording.

Calculating the Device Rotation Angle

You can call once(type: SensorId.GRAVITY, callback: Callback<GravityResponse>) to obtain the data of the gravity sensor in the x, y, and z directions and calculate the device rotation angle (specified by deviceDegree). The following is an example.

If accelerometer data cannot be obtained, request the permission ohos.permission.ACCELEROMETER. For details about how to request permissions, see Declaring Permissions. For details about how to obtain sensor data, see Sensor Development (ArkTS).

getRealData(data: sensor.GravityResponse): number {
  let getDeviceDegree: number = 0;
  let x = data.x;
  let y = data.y;
  let z = data.z;
  if ((x * x + y * y) * 3 < z * z) {
    return getDeviceDegree;
  } else {
    try {
      let sd: Decimal = Decimal.atan2(y, -x);
      let sc: Decimal = Decimal.round(Number(sd) / 3.141592653589 * 180);
      getDeviceDegree = 90 - Number(sc);
      getDeviceDegree = getDeviceDegree >= 0 ? getDeviceDegree % 360 : getDeviceDegree % 360 + 360;
    } catch (error) {
      let err = error as BusinessError;
      console.error(`decimal failed, error: ${err.code}`);
    }
  }
  return getDeviceDegree;
}

async getGravity() : Promise<number> {
  let data: sensor.Sensor[];
  let isSupported: boolean = false;
  try {
    data = await sensor.getSensorList();
  } catch (error) {
    let err = error as BusinessError;
    console.error(`getSensorList failed, error: ${err.code}`);
    return -1; // Return the default value in the case of an exception.
  }

  for (let i = 0; i < data.length; i++) {
    if (data[i].sensorId === sensor.SensorId.GRAVITY) {
      isSupported = true;
      break;
    }
  }
  try {
    if (isSupported === true) {
      const promise: Promise<number> = new Promise((resolve) => {
        sensor.once(sensor.SensorId.GRAVITY, (data: sensor.GravityResponse) => {
          resolve(this.getRealData(data));
        });
      })
      return promise;
    } else {
      const promise: Promise<number> = new Promise((resolve) => {
        sensor.once(sensor.SensorId.ACCELEROMETER, (data: sensor.AccelerometerResponse) => {
          resolve(this.getRealData(data as sensor.GravityResponse));
        });
      })
      return promise;
    }
  } catch (error) {
    let err = error as BusinessError;
    console.error(`gePromise failed, error: ${err.code}`);
    return -1; // Return the default value in the case of an exception.
  }
}

// Obtain the device rotation degree.
async getCurrentDeviceDegree() : Promise<number> {
  getDeviceDegree = await getGravity(); // Use await.
  return getDeviceDegree;
}

Correcting the Video Orientation in Video Calls

During video calls between two devices, there might be discrepancies in how each device is held. To address this, it is recommended that you correct the video orientation on the local device before transmitting it to the remote device over the network. For details about how to correct the video orientation, see Normalization of Preview Angles in Self-Drawing Scenarios.

Lossless Image Output from the Camera

On some foldable devices, the device natural directions under different folding states change. As a result, the actual camera lens installation angles vary according to the folding states. To shield the differences between the devices and make the camera lens installation angles to be the same in different folding states, the system automatically adjusts the directions of the images captured by the cameras in some folding states (by rotation and cutting) and the camera lens installation angles. Therefore, there is a field of view (FOV) loss, which may reduce the visible range of the preview, photographing, and recording by the cameras. Therefore, to implement lossless image output, you can call usePhysicalCameraOrientation. Specifically:

Check whether the camera lens installation angles of the devices are variable through isPhysicalCameraOrientationVariable.

  1. When the camera lens installation angles are not variable, the image output of the cameras in different folding states is lossless.

  2. When the camera lens installation angles are variable:

    To implement lossless image output, call getPhysicalCameraOrientation to obtain the actual camera lens installation angles of the devices in the current folding state after the application completes camera rotation adaptation, because the camera lens installation angles are related the camera rotation. Then call usePhysicalCameraOrientation to output lossless images. (When the camera lens installation angles are not variable, calling usePhysicalCameraOrientation will return error code 7400102. Implementing lossless image output of the cameras when the camera rotation is not adapted will result in an error in preview, photographing, and recording.) You are advised to call usePhysicalCameraOrientation following createCameraInput to implement lossless image output.

The sample code is as follows:

enablePhysicalCameraOrientation(cameraInput: camera.CameraInput) {
  // Query whether the camera lens installation angle is variable.
  let isVariable: boolean = cameraInput.isPhysicalCameraOrientationVariable();

  if (isVariable) {
    // Obtain the actual camera lens installation angle in the current folding state.
    let physicalOrientation: number = cameraInput.getPhysicalCameraOrientation();
    console.info(`physical Orientation is ${physicalOrientation}`);

    // Select whether to use the actual camera lens installation angle to achieve lossless image output.
    let isUsed: boolean = true;
    cameraInput.usePhysicalCameraOrientation(isUsed);
  }
}

Troubleshooting

[h2]Specifying the Size of XComponent to Prevent Image Distortion After Rotation

Image distortion can occur if the image resolution does not match the aspect ratio of the XComponent. For example, when the application layer specifies a 1920 × 1080 (16:9) resolution for both portrait and landscape orientations, a raw image in a 4:3 aspect ratio is initially output, and then, the image will be cropped to fit the 16:9 aspect ratio before being passed to the application layer. As a result, no matter how the phone is oriented, the data received by the application layer will consistently be in a 16:9 aspect ratio. The specific illustration is as follows.

Device and Lens Direction Processing Diagram XComponent Layout

Device conditions:

The mobile phone is in portrait mode, with the charging port facing downwards.

A rear camera is used to take photos.

Angles determined:

- Lens installation angle of the rear camera = 90°

- Screen rotation angle = 0°, Display.rotation = 0

- Image preview rotation angle = 0° + 90° = 90°

The output image is rotated 90 degrees relative to the final imaging, with the layout's width and height interchanged with the image's width and height.

Device conditions:

The mobile phone is in landscape mode, with the charging port facing rightward.

A rear camera is used to take photos.

Angles determined:

- Lens installation angle of the rear camera = 90°

- Screen rotation angle = 270°, Display.rotation = 3

- Image preview rotation angle = 270° + 90° = 360° = 0°

The output image aligns perfectly with the final imaging, maintaining a consistent aspect ratio between the layout and the image.

As shown in the preceding figure, when the mobile phone switches from portrait to landscape orientation, the image output ratio is always 16:9, but the angle between the lens and the screen display orientation changes from 90 degrees to 0 degrees. Keeping the layout at a 9:16 ratio would distort the image when displaying 16:9 image data within a 9:16 space. To ensure the image displays correctly, the layout's aspect ratio should be adjusted to 16:9 in landscape mode.

To achieve this, listen for the width and height of the XComponent as state variables. Use Window.on('windowSizeChange') to detect window changes and adjust the layout's aspect ratio based on the angle difference between the screen rotation (specified by Display.rotation) and the camera lens orientation (specified by CameraDevice.cameraOrientation). This ensures the layout dynamically adapts to window changes.

For implementation, in pages that involve switching between portrait and landscape modes, listen for window changes within the aboutToAppear lifecycle function.

import { bundleManager } from '@kit.AbilityKit';
import { display } from '@kit.ArkUI';
import { common } from '@kit.AbilityKit';
import { BusinessError, deviceInfo  } from '@kit.BasicServicesKit';

// ....
let previewOutput : camera.PreviewOutput; // Create a scenario-specific preview output stream.
let cameraDevice : camera.CameraDevice; // Select a camera device based on the use case.
@Entry
@Component
struct Index {
  @State mXComponentWidth: number = 1280;
  @State mXComponentHeight: number = 720;
  @State mRotate: number = 0;
  @State mConfigRatio: number = 16 / 9;
  private targetVersion: number = 0;
  private mWindowHeight = 0;
  private mWindowWidth = 0;

  private windowClass = (this.getUIContext().getHostContext() as common.UIAbilityContext).windowStage.getMainWindowSync();
  getBundleInfoForSelf() { // Obtain the build version of the application.
    let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION | bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_METADATA;
    try {
      bundleManager.getBundleInfoForSelf(bundleFlags).then((data) => {
        console.info(`getBundleInfoForSelf successfully. Data: ${data.targetVersion}`);
        this.targetVersion = data.targetVersion;
      }).catch((err: BusinessError) => {
        console.error(`getBundleInfoForSelf failed ${err}`);
      });
    } catch (err) {
      let message = (err as BusinessError).message;
      console.error(`getBundleInfoForSelf failed ${message}`);
    }
  }

  isIsolateForSpecialType(): boolean { // Compatible with tablets of API versions earlier than 14.
    return deviceInfo.deviceType == "tablet" && this.targetVersion <= 50000013;
  }

  aboutToAppear(): void {
    this.updateXComponentSize();
    this.getBundleInfoForSelf();
    this.windowClass.on('windowSizeChange', (size) => {
      this.mWindowWidth = size.width;
      this.mWindowHeight = size.height;
      this.updateXComponentSize();
    });
    let rotation : number = 0;
    try {
      rotation = display.getDefaultDisplaySync().rotation;
      this.mRotate = rotation * camera.ImageRotation.ROTATION_90;
    } catch (error) {
      const err = error as BusinessError;
      console.error(`Failed to get display rotation: ${err.code}, ${err.message}`);
      this.mRotate = 0;
    }
    display.on('change', () => {
      if (this.mRotate!= rotation * camera.ImageRotation.ROTATION_90) {
        this.mRotate= rotation * camera.ImageRotation.ROTATION_90; // Obtain the screen rotation angle.
        this.updateXComponentSize();
        let imageRotation = this.getImageRotation();
        if (!imageRotation) {
          console.error(`current get image rotation is undefined`);
          return;
        }
        let previewRotation = previewOutput.getPreviewRotation(imageRotation); // previewOutput is the created preview stream.
        previewOutput.setPreviewRotation(previewRotation, false);
      }
    });
  }
  getImageRotation() : camera.ImageRotation | undefined {
    let displayRotation : number= 0;
    try {
      displayRotation = display.getDefaultDisplaySync().rotation
    } catch (error) {
      const err = error as BusinessError;
      console.error(`Failed to get display rotation: ${err.code}, ${err.message}`);
      return undefined;
    }
    let imageRotation = displayRotation * camera.ImageRotation.ROTATION_90;
    return imageRotation;
  }
  updateXComponentSize(): void {
    let angleDiff = (this.mRotate+ cameraDevice?.cameraOrientation) % 360;
    if (this.isIsolateForSpecialType()) { // If the device is a tablet and its API version is earlier than 14, this logic will be applied.
      if (angleDiff === 90 || angleDiff=== 270) {
      this.mXComponentWidth = this.mConfigRatio * this.mWindowHeight;
      this.mXComponentHeight = this.mWindowHeight;
    } else {
      this.mXComponentWidth = this.mWindowWidth;
      this.mXComponentHeight = this.mConfigRatio * this.mWindowWidth; // 1920 *1080
    }
    } else { // If the device is not a tablet or its API version is not earlier than 14, this logic will be applied.
      if (angleDiff === 90 || angleDiff=== 270) {
        this.mXComponentWidth = this.mWindowWidth;
        this.mXComponentHeight = this.mConfigRatio * this.mWindowWidth; // 1920 *1080
      } else {
        this.mXComponentWidth = this.mConfigRatio * this.mWindowHeight;
        this.mXComponentHeight = this.mWindowHeight;
      }
    }
  }

  async aboutToDisAppear(): Promise<void> {
    display.off('change');
    this.windowClass.off('windowSizeChange');
    // Unregister the callback.
  }
  build() {
    // Add the UI processing logic based on the use case.
  }
}

In addition to specifying the width and height of the XComponent, you can achieve adaptive size display and centered cropping display of images by setting renderFit of the XComponent. For details, see renderFit.

[h2]Normalization of Preview Angles in Self-Drawing Scenarios

In self-drawing scenarios, for the rear camera, you can obtain the rotation angle by calling getPreviewRotation and orient the image correctly. For the front camera, due to differences in horizontal and vertical mirroring, you need to first normalize the image angle of the front camera, orient the image correctly, and decide whether to perform mirroring based on service requirements.

Below is the PixelMap processing method:

import { camera } from '@kit.CameraKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { image } from '@kit.ImageKit';
import { display } from '@kit.ArkUI';

let previewOutputReceiver: camera.PreviewOutput | undefined = undefined; // Define the callback stream.
let curCameraPosition = camera.CameraPosition.CAMERA_POSITION_FRONT; // Define the camera position (front camera used as an example).
// .....
function  onImageArrival(receiver: image.ImageReceiver): void {
  receiver.on('imageArrival', () => { // imageRecevier callback.
    // Obtain an image.
    receiver.readNextImage((err: BusinessError, nextImage: image.Image) => {
      if (err || nextImage === undefined) {
        console.error('readNextImage failed');
        return;
      }
      // Parse the image.
      nextImage.getComponent(image.ComponentType.JPEG, async (err: BusinessError, imgComponent: image.Component) => {
        if (err || imgComponent === undefined) {
          console.error('getComponent failed');
        }

        if (imgComponent.byteBuffer) {
          let width = nextImage.size.width; // Obtain the image width.
          let height = nextImage.size.height; // Obtain the image height.
          let stride = imgComponent.rowStride; // Obtain the image stride.
          // The value of stride is the same as that of width.
          if (stride == width) {
            let pixelMap = await image.createPixelMap(imgComponent.byteBuffer, {
              size: { height: height, width: width },
              srcPixelFormat: image.PixelMapFormat.NV21, // Here NV21 is used as an example.
            })
            updatePixelMap(pixelMap);
          } else {
            // The value of stride is different from that of width.
            const dstBufferSize = width * height * 1.5 // For example, for NV21 (images in YUV_420_SP format), the formula for calculating the YUV_420_SP memory is as follows: YUV_420_SP memory = Width * Height + (Width * Height)/2
            const dstArr = new Uint8Array(dstBufferSize)
            for (let j = 0; j < height * 1.5; j++) {
              const srcBuf = new Uint8Array(imgComponent.byteBuffer, j * stride, width)
              dstArr.set(srcBuf, j * width)
            }
            let pixelMap = await image.createPixelMap(dstArr.buffer, {
              size: { height: height, width: width },
              srcPixelFormat: image.PixelMapFormat.NV21, // Here NV21 is used as an example.
            });
            updatePixelMap(pixelMap);
          }
        } else {
          console.error('byteBuffer is null');
        }
        // Release the resource when the buffer is not in use.
        // If an asynchronous operation is performed on the buffer, call nextImage.release() to release the resource after the asynchronous operation is complete.
        nextImage.release();
        console.info('image process done');
      })
    })
  })
}
async function updatePixelMap(pixelMap: image.PixelMap): Promise<void> {
  let rotation : number = 0;
  try {
    rotation = display.getDefaultDisplaySync().rotation * camera.ImageRotation.ROTATION_90;
  } catch (error) {
    const err = error as BusinessError;
    console.error(`Failed to get display rotation: ${err.code}, ${err.message}`);
    return;
  }
  let angle = previewOutputReceiver?.getPreviewRotation(rotation);
  if (angle === undefined) {
    return;
  }
  // If setPreviewRotation has been called on previewOutput in display.on, you do not need to call it again here.
  previewOutputReceiver?.setPreviewRotation(angle);
  if (curCameraPosition === camera.CameraPosition.CAMERA_POSITION_FRONT) {
    if (rotation ===90 || rotation === 270) {
      angle = (angle + 180 ) % 360;
    }
    await pixelMap.rotate(angle);
    await pixelMap.flip(true, false);
  } else {
    await pixelMap.rotate(angle);
  }
}

[h2]Cross-Device Adaptation

To ensure compatibility across multiple devices, perform the following steps:

  1. Select an appropriate preview resolution based on the screen ratio.

  2. Obtain a new ratio from the chosen preview resolution using the width and height.

  3. Calculate the width and height of the XComponent based on the new ratio. For details, see Specifying the Size of XComponent to Prevent Image Distortion After Rotation. Apply mConfigRatio to calculate the layout width and height.

    For a foldable device, the screen ratio must be recalculated each time the foldable screen lens changes.

let mConfigRatio: number = 16 / 9; // Set the initial resolution ratio. Here the 16:9 aspect ratio is used as an example.
let reConfigType : number = 720;
let previewProfileObj: camera.Profile = {
  format: 1003,
  size: {
    width: 1280,
    height: 720
  }
};
// Calculate the ratio based on the screen dimensions, longer side divided by the shorter side.
function getConfigRation(cameraDevice: camera.CameraDevice, cameraManager: camera.CameraManager) : number {
  let previewProfile = getSurfaceSize(cameraDevice, mConfigRatio, cameraManager); // Obtain the resolution that is closest to the desired ratio.
  if (previewProfile === undefined || previewProfile.size === undefined) {
    return 0;
  }
  mConfigRatio = previewProfile.size.width / previewProfile.size.height; // Recalculate the display width and height using the new ratio.
  return mConfigRatio;
}

// Obtain the resolution that is closest to the screen dimensions.
function getSurfaceSize(cameraDevice: camera.CameraDevice, configRatio: number, cameraManager: camera.CameraManager): camera.Profile | undefined {
  console.info(`previewProfiles is ${configRatio}`);
  let cameraOutputCapability =
    cameraManager.getSupportedOutputCapability(cameraDevice, camera.SceneMode.NORMAL_PHOTO); // Here NORMAL_PHOTO is used as an example.
  return getPreviewProfile(cameraOutputCapability, configRatio);
}
function getPreviewProfile(cameraOutputCapability: camera.CameraOutputCapability, configRatio: number): camera.Profile | undefined {
  let previewProfiles = cameraOutputCapability.previewProfiles;
  if (previewProfiles.length < 1) {
    return undefined;
  }
  console.info(`previewProfiles this.foramt: ${previewProfileObj.format} configRatio = ${configRatio}`);
  let optimalSize: camera.Profile|undefined;
  let minDiff = Number.MAX_VALUE;
  // Calculate the screen's aspect ratio.
  for (let i = 0; i < previewProfiles.length; i++) {
    if (previewProfiles[i].format !== previewProfileObj.format) {
      continue;
    }
    let ratio = previewProfiles[i].size.width / previewProfiles[i].size.height; // 1088*1080
    // Check whether the aspect ratio is within an acceptable range.
    if (Math.abs(ratio - configRatio) > 0.2) continue; // You can adjust the error margin of 0.2 as needed.
    // Select the resolution that is closest to the desired ratio.
    if (Math.abs(previewProfiles[i].size.height - reConfigType) < minDiff) {
      optimalSize = previewProfiles[i];
      minDiff = Math.abs(previewProfiles[i].size.height - reConfigType);
    }
  }

  // If no suitable resolution is found, select the first available one.
  if (optimalSize === undefined) {
    minDiff = Number.MAX_VALUE;
    for (let i = 0; i < previewProfiles.length; i++) {
      if (previewProfiles[i].format !== previewProfileObj.format) {
        continue;
      }
      if (Math.abs(previewProfiles[i].size.height - reConfigType) < minDiff) { // 720
        optimalSize = previewProfiles[i];
        minDiff = Math.abs(previewProfiles[i].size.height - reConfigType);
      }
    }
  }
  return optimalSize;
}

[h2]No Mirroring During Photo Capture

Change the mirror setting in PhotoCaptureSetting.

// this.photoOutput represents the photo output, and this.getDeviceDegree represents the gravity angle.
let photoSettings: camera.PhotoCaptureSetting = {
  quality: camera.QualityLevel.QUALITY_LEVEL_HIGH,
  mirror: this.photoOutput?.isMirrorSupported() // Check whether mirroring for photos is supported. The value true means that mirroring is supported, and false means the opposite.
};
 // ... Omitted code for obtaining the settings.
this.photoRotation = getPhotoRotation(this.photoOutput!!,this.getDeviceDegree)
photoSettings.rotation = this.photoRotation // Specify the rotation angle for the photo.