HarmonyOS 进入页面拍照,页面显示有点变型,横排或竖屏有拉伸或者压缩,页面有很多红点

进入页面拍照,相机页面显示有点变形,横排或竖屏有拉伸或者压缩画面,点击拍照后照片会在相册中,可以看相册的照片很多红黄蓝点。

HarmonyOS
2025-01-09 17:59:40
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
superinsect

照片模糊和拉伸问题,模糊问题可以调整拍照输出流的分辨率,拉伸问题要确保分辨率宽高比和xcomponent的高宽比值接近,可基于此思路和如下代码调整这两点,以达到最佳拍照效果:

import camera from '@ohos.multimedia.camera';
import image from '@ohos.multimedia.image';
import { BusinessError } from '@ohos.base';
import common from '@ohos.app.ability.common';
import fs from '@ohos.file.fs';

import { abilityAccessCtrl } from '@kit.AbilityKit';
import photoAccessHelper from '@ohos.file.photoAccessHelper';
import { promptAction } from '@kit.ArkUI';

let context = getContext(this);
let cameraArray: Array<camera.CameraDevice>
let cameraManager: camera.CameraManager
let cameraInput: camera.CameraInput | undefined = undefined;
let previewOutput: camera.PreviewOutput | undefined = undefined;
let photoSession: camera.PhotoSession | undefined = undefined;

async function savePicture(buffer: ArrayBuffer, img: image.Image): Promise<void> {
  let accessHelper: photoAccessHelper.PhotoAccessHelper = photoAccessHelper.getPhotoAccessHelper(context);
  let options: photoAccessHelper.CreateOptions = {
    title: Date.now().toString()
  };
  let photoUri: string = await accessHelper.createAsset(photoAccessHelper.PhotoType.IMAGE, 'jpg', options);
  //createAsset的调用需要ohos.permission.READ_IMAGEVIDEO和ohos.permission.WRITE_IMAGEVIDEO的权限
  let file: fs.File = fs.openSync(photoUri, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
  await fs.write(file.fd, buffer);
  fs.closeSync(file);
  img.release();
}

function setPhotoOutputCb(photoOutput: camera.PhotoOutput): void {
  //设置回调之后,调用photoOutput的capture方法,就会将拍照的buffer回传到回调中
  photoOutput.on('photoAvailable', (errCode: BusinessError, photo: camera.Photo): void => {
    console.info('getPhoto start');
    console.info(`err: ${JSON.stringify(errCode)}`);
    if (errCode || photo === undefined) {
      console.error('getPhoto failed');
      return;
    }
    let imageObj = photo.main;
    imageObj.getComponent(image.ComponentType.JPEG, (errCode: BusinessError, component: image.Component): void => {
      console.info('getComponent start');
      if (errCode || component === undefined) {
        console.error('getComponent failed');
        return;
      }
      let buffer: ArrayBuffer;
      if (component.byteBuffer) {
        buffer = component.byteBuffer;
      } else {
        console.error('byteBuffer is null');
        return;
      }
      savePicture(buffer, imageObj);
    });
  });
}

function onPhotoOutputCaptureStart(photoOutput: camera.PhotoOutput): void {
  photoOutput.on('photoAssetAvailable', (err: BusinessError, photoAsset: photoAccessHelper.PhotoAsset) => {
    console.info(`photo capture started, captureId :`);
  });
}

interface GeneratedObjectLiteralInterface_1 {
  // 位置信息,经纬度
  latitude: number;
  longitude: number;
  altitude: number;
}

@Entry
@Component
struct PaiZ {
  @State message: string = 'Hello World';
  private mXComponentController: XComponentController = new XComponentController;
  private surfaceId: string = '-1';
  @State photoOutput: camera.PhotoOutput | undefined = undefined;
  private handlePhotoAssetCb: (photoAsset: photoAccessHelper.PhotoAsset) => void = () => {
  };

  setSavePictureCallback(callback: (photoAsset: photoAccessHelper.PhotoAsset) => void): void {
    this.handlePhotoAssetCb = callback;
  }

  aboutToAppear() {
    //申请权限
    let context = getContext() as common.UIAbilityContext;
    abilityAccessCtrl.createAtManager().requestPermissionsFromUser(context, ['ohos.permission.CAMERA']).then(() => {
      this.mXComponentController.setXComponentSurfaceSize({ surfaceWidth: 1920, surfaceHeight: 1080 });
      // 获取Surface ID
      this.surfaceId = this.mXComponentController.getXComponentSurfaceId();
      this.cameraShootingCase(this.surfaceId);
    });
  }

  build() {
    Row() {
      Column() {
        Button("拍照").onClick(() => {
          this.takePicture()
          promptAction.showToast({ message: `拍摄成功` })
        })
        // 创建XComponent
        XComponent({
          id: '',
          type: 'surface',
          libraryname: '',
          controller: this.mXComponentController
        })
          .onLoad(() => {
            // 设置Surface宽高(1920*1080),预览尺寸设置参考前面 previewProfilesArray 获取的当前设备所支持的预览分辨率大小去设置
            // this.mXComponentController.setXComponentSurfaceSize({ surfaceWidth: 1920, surfaceHeight: 1080 });
            this.mXComponentController.setXComponentSurfaceSize({ surfaceWidth: 2560, surfaceHeight: 1080 });
            // 获取Surface ID
            this.surfaceId = this.mXComponentController.getXComponentSurfaceId();
            this.cameraShootingCase(this.surfaceId);
          })
          .width('1600px')
          .height('2560px')
      }
      .width('100%')
    }
    .backgroundColor(Color.Gray)
    .height('100%')
  }

  async photoAssetAvailableCallback(err: BusinessError, photoAsset: photoAccessHelper.PhotoAsset): Promise<void> {
    // Check for an error first
    if (err) {
      console.info(`photoAssetAvailable error: ${JSON.stringify(err)}.`);
      return;
    }
    console.info('photoOutPutCallBack photoAssetAvailable', JSON.stringify(photoAsset));
    try {
      let assetChangeRequest: photoAccessHelper.MediaAssetChangeRequest =
        new photoAccessHelper.MediaAssetChangeRequest(photoAsset);
      assetChangeRequest.saveCameraPhoto();
      let phAccessHelper = photoAccessHelper.getPhotoAccessHelper(context);
      await phAccessHelper.applyChanges(assetChangeRequest);
      console.info('apply saveCameraPhoto successfully');
    } catch (err) {
      console.error(`apply saveCameraPhoto failed with error: ${err.code}, ${err.message}`);
    }
  }

  async takePicture(): Promise<void> {

    let photoSettings: camera.PhotoCaptureSetting = {
      rotation: camera.ImageRotation.ROTATION_0,
      quality: camera.QualityLevel.QUALITY_LEVEL_HIGH,
      location: ({
        // 位置信息,经纬度
        latitude: 12.9698,
        longitude: 77.75,
        altitude: 1000,
      } as GeneratedObjectLiteralInterface_1),
      mirror: false,
    };

    let that = this
    this.photoOutput?.on("photoAssetAvailable", this.photoAssetAvailableCallback);

    const a = await this.photoOutput?.capture(photoSettings, (err) => {
      console.log(JSON.stringify(err));
    });
    console.log(JSON.stringify(a));
    AppStorage.set('isRefresh', true);
  }

  async Qhsxt(surfaceId: string) {
    photoSession?.stop()
    photoSession?.beginConfig()
    photoSession?.removeInput(cameraInput)
    // photoSession?.removeOutput(previewOutput)
    photoSession?.commitConfig()
    await cameraInput?.close()
    // cameraInput=undefined;
    try {
      cameraInput = cameraManager.createCameraInput(cameraArray[1]);
    } catch (error) {
      let err = error as BusinessError;
      console.error('Failed to createCameraInput errorCode = ' + err.code);
    }
    if (cameraInput === undefined) {
      return;
    }
    await cameraInput.open();
    photoSession?.beginConfig()
    try {
      photoSession?.addInput(cameraInput);
    } catch (error) {
      let err = error as BusinessError;
      console.error('Failed to addInput. errorCode = ' + err.code);
    }
    photoSession?.commitConfig()
    photoSession?.start()
  }

  async cameraShootingCase(surfaceId: string): Promise<void> {
    cameraManager = await camera.getCameraManager(context);
    // 创建CameraManager对象
    if (!cameraManager) {
      console.error("camera.getCameraManager error");
      return;
    }
    // 监听相机状态变化
    cameraManager.on('cameraStatus', (err: BusinessError, cameraStatusInfo: camera.CameraStatusInfo) => {
      console.info(`camera : ${cameraStatusInfo.camera.cameraId}`);
      console.info(`status: ${cameraStatusInfo.status}`);
    });

    // 获取相机列表
    cameraArray = cameraManager.getSupportedCameras();
    if (cameraArray.length <= 0) {
      console.error("cameraManager.getSupportedCameras error");
      return;
    }

    for (let index = 0; index < cameraArray.length; index++) {
      console.info('cameraId : ' + cameraArray[index].cameraId); // 获取相机ID
      console.info('cameraPosition : ' + cameraArray[index].cameraPosition); // 获取相机位置
      console.info('cameraType : ' + cameraArray[index].cameraType); // 获取相机类型
      console.info('connectionType : ' + cameraArray[index].connectionType); // 获取相机连接类型
    }

    // 创建相机输入流
    try {
      cameraInput = cameraManager.createCameraInput(cameraArray[0]);
    } catch (error) {
      let err = error as BusinessError;
      console.error('Failed to createCameraInput errorCode = ' + err.code);
    }
    if (cameraInput === undefined) {
      return;
    }

    // 监听cameraInput错误信息
    let cameraDevice: camera.CameraDevice = cameraArray[0];
    cameraInput.on('error', cameraDevice, (error: BusinessError) => {
      console.error(`Camera input error code: ${error.code}`);
    })

    // 打开相机
    await cameraInput.open();

    // 获取支持的模式类型
    let sceneModes: Array<camera.SceneMode> = cameraManager.getSupportedSceneModes(cameraArray[0]);
    let isSupportPhotoMode: boolean = sceneModes.indexOf(camera.SceneMode.NORMAL_PHOTO) >= 0;
    if (!isSupportPhotoMode) {
      console.error('photo mode not support');
      return;
    }
    // 获取相机设备支持的输出流能力
    let cameraOutputCap: camera.CameraOutputCapability =
      cameraManager.getSupportedOutputCapability(cameraArray[0], camera.SceneMode.NORMAL_PHOTO);
    if (!cameraOutputCap) {
      console.error("cameraManager.getSupportedOutputCapability error");
      return;
    }
    console.info("outputCapability: " + JSON.stringify(cameraOutputCap));

    let previewProfilesArray: Array<camera.Profile> = cameraOutputCap.previewProfiles;
    if (!previewProfilesArray) {
      console.error("createOutput previewProfilesArray == null || undefined");
    }

    let photoProfilesArray: Array<camera.Profile> = cameraOutputCap.photoProfiles;
    if (!photoProfilesArray) {
      console.error("createOutput photoProfilesArray == null || undefined");
    }
    console.log(`当前预览流的分辨率为:${JSON.stringify(photoProfilesArray)}`)

    // 创建预览输出流,其中参数 surfaceId 参考上文 XComponent 组件,预览流为XComponent组件提供的surface

    try {
      previewOutput = cameraManager.createPreviewOutput(previewProfilesArray[0], surfaceId);
    } catch (error) {
      let err = error as BusinessError;
      console.error(`Failed to create the PreviewOutput instance. error code: ${err.code}`);
    }
    if (previewOutput === undefined) {
      return;
    }
    // 监听预览输出错误信息
    previewOutput.on('error', (error: BusinessError) => {
      console.error(`Preview output error code: ${error.code}`);
    });
    // 创建拍照输出流

    try {
      this.photoOutput = cameraManager.createPhotoOutput(photoProfilesArray[9]);
    } catch (error) {
      let err = error as BusinessError;
      console.error('Failed to createPhotoOutput errorCode = ' + err.code);
    }
    if (this.photoOutput === undefined) {
      return;
    }

    //调用上面的回调函数来保存图片
    onPhotoOutputCaptureStart(this.photoOutput);

    //创建会话

    try {
      photoSession = cameraManager.createSession(camera.SceneMode.NORMAL_PHOTO) as camera.PhotoSession;
    } catch (error) {
      let err = error as BusinessError;
      console.error('Failed to create the session instance. errorCode = ' + err.code);
    }
    if (photoSession === undefined) {
      return;
    }
    // 监听session错误信息
    photoSession.on('error', (error: BusinessError) => {
      console.error(`Capture session error code: ${error.code}`);
    });

    // 开始配置会话
    try {
      photoSession.beginConfig();
    } catch (error) {
      let err = error as BusinessError;
      console.error('Failed to beginConfig. errorCode = ' + err.code);
    }

    // 向会话中添加相机输入流
    try {
      photoSession.addInput(cameraInput);
    } catch (error) {
      let err = error as BusinessError;
      console.error('Failed to addInput. errorCode = ' + err.code);
    }

    // 向会话中添加预览输出流
    try {
      photoSession.addOutput(previewOutput);
    } catch (error) {
      let err = error as BusinessError;
      console.error('Failed to addOutput(previewOutput). errorCode = ' + err.code);
    }

    // 向会话中添加拍照输出流
    try {
      photoSession.addOutput(this.photoOutput);
    } catch (error) {
      let err = error as BusinessError;
      console.error('Failed to addOutput(photoOutput). errorCode = ' + err.code);
    }
    // 提交会话配置
    await photoSession.commitConfig();

    // 启动会话
    await photoSession.start().then(() => {
      console.info('Promise returned to indicate the session start success.');
    });
    // 判断设备是否支持闪光灯
    let flashStatus: boolean = false;
    try {
      flashStatus = photoSession.hasFlash();
    } catch (error) {
      let err = error as BusinessError;
      console.error('Failed to hasFlash. errorCode = ' + err.code);
    }
    console.info('Returned with the flash light support status:' + flashStatus);
    if (flashStatus) {
      // 判断是否支持自动闪光灯模式
      let flashModeStatus: boolean = false;
      try {
        let status: boolean = photoSession.isFlashModeSupported(camera.FlashMode.FLASH_MODE_AUTO);
        flashModeStatus = status;
      } catch (error) {
        let err = error as BusinessError;
        console.error('Failed to check whether the flash mode is supported. errorCode = ' + err.code);
      }
      if (flashModeStatus) {
        // 设置自动闪光灯模式
        try {
          photoSession.setFlashMode(camera.FlashMode.FLASH_MODE_AUTO);
        } catch (error) {
          let err = error as BusinessError;
          console.error('Failed to set the flash mode. errorCode = ' + err.code);
        }
      }
    }
    // 判断是否支持连续自动变焦模式
    let focusModeStatus: boolean = false;
    try {
      let status: boolean = photoSession.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_AUTO);
      focusModeStatus = status;
    } catch (error) {
      let err = error as BusinessError;
      console.error('Failed to check whether the focus mode is supported. errorCode = ' + err.code);
    }

    if (focusModeStatus) {
      // 设置连续自动变焦模式
      try {
        photoSession.setFocusMode(camera.FocusMode.FOCUS_MODE_AUTO);
      } catch (error) {
        let err = error as BusinessError;
        console.error('Failed to set the focus mode. errorCode = ' + err.code);
      }
    }

    // 获取相机支持的可变焦距比范围
    let zoomRatioRange: Array<number> = [];
    try {
      zoomRatioRange = photoSession.getZoomRatioRange();
    } catch (error) {
      let err = error as BusinessError;
      console.error('Failed to get the zoom ratio range. errorCode = ' + err.code);
    }
    if (zoomRatioRange.length <= 0) {
      return;
    }
    // 设置可变焦距比
    try {
      photoSession.setZoomRatio(zoomRatioRange[0]);
    } catch (error) {
      let err = error as BusinessError;
      console.error('Failed to set the zoom ratio value. errorCode = ' + err.code);
    }
  }
}
分享
微博
QQ
微信
回复
2025-01-09 20:31:55
相关问题
HarmonyOS 页面骨架
606浏览 • 0回复 待解决
page页面如何设置为横显示
2108浏览 • 1回复 待解决
页面基类或者页面钩子函数
664浏览 • 0回复 待解决
进入相册拍照选择图片做头像
13955浏览 • 2回复 已解决