HarmonyOS Camera Kit(相机服务)预览输出流与相片输出流不一致

HarmonyOS
2天前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
aquaa
import { camera } from '@kit.CameraKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { image } from '@kit.ImageKit';
import { photoAccessHelper } from '@kit.MediaLibraryKit';
import { abilityAccessCtrl, PermissionRequestResult, Permissions } from '@kit.AbilityKit';
import { promptAction } from '@kit.ArkUI';
import { fileIo } from '@kit.CoreFileKit';

const TAG = '[CameraDemo]';

@Entry
@Component
struct CameraDemo {
  context: Context = getContext(this) as Context;
  @State pixelMap: image.PixelMap | undefined = undefined;
  @State finalPixelMap: image.PixelMap | undefined = undefined;
  @State buffer: ArrayBuffer | undefined = undefined;
  @State surfaceId: string = '';
  @State hasPicture: boolean = false;
  @State fileNames: string[] = [];
  @State imageSize: image.Size = { width: 1920, height: 1080 };
  @State saveButtonOptions: SaveButtonOptions = {
    icon: SaveIconStyle.FULL_FILLED,
    text: SaveDescription.SAVE_IMAGE,
    buttonType: ButtonType.Capsule
  } // 设置安全控件按钮属性
  private mXComponentController: XComponentController = new XComponentController;
  private cameraManager: camera.CameraManager | undefined = undefined;
  private cameraSession: camera.PhotoSession | undefined = undefined;
  private photoOutput: camera.PhotoOutput | undefined = undefined;
  private cameraInput: camera.CameraInput | undefined = undefined;
  private previewOutput: camera.PreviewOutput | undefined = undefined;
  private imageReceiver: image.ImageReceiver | undefined = undefined;

  aboutToAppear(): void {
    let permissions: Array<Permissions> = [
      'ohos.permission.CAMERA',
      'ohos.permission.WRITE_MEDIA',
      'ohos.permission.READ_MEDIA',
      'ohos.permission.MEDIA_LOCATION',
    ];
    let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager();
    // requestPermissionsFromUser会判断权限的授权状态来决定是否唤起弹窗
    atManager.requestPermissionsFromUser(this.context, permissions).then((data: PermissionRequestResult) => {
      let grantStatus: Array<number> = data.authResults;
      let length: number = grantStatus.length;
      for (let i = 0; i < length; i++) {
        if (grantStatus[i] != 0) {
          // 用户拒绝授权,提示用户必须授权才能访问当前页面的功能,并引导用户到系统设置中打开相应的权限
          return;
        }
      }
      console.info(`${TAG} Success to request permissions from user. authResults is ${grantStatus}.`);
    }).catch((err: BusinessError) => {
      console.error(`${TAG} Failed to request permissions from user. Code is ${err.code}, message is ${err.message}`);
    })
  }

  createCameraManager() {
    // 创建CameraManager对象
    let cameraManager: camera.CameraManager = camera.getCameraManager(this.context);
    if (!cameraManager) {
      console.error('CameraDemo camera.getCameraManager error');
      return;
    }
    this.cameraManager = cameraManager
    // 监听相机状态变化
    this.cameraManager.on('cameraStatus', (err: BusinessError, cameraStatusInfo: camera.CameraStatusInfo) => {
      console.info(`CameraDemo camera: ${cameraStatusInfo.camera.cameraId}, status: ${cameraStatusInfo.status}`);
    });
  }

  build() {
    Column() {
      Column({ space: 20 }) {
        if (this.hasPicture) {
          Image(this.finalPixelMap)
            .objectFit(ImageFit.Fill)
            .width('100%')
            .height(300)

          SaveButton(this.saveButtonOptions)// 创建安全控件按钮
            .onClick(async (event, result: SaveButtonOnClickResult) => {
              if (result == SaveButtonOnClickResult.SUCCESS) {
                if (this.finalPixelMap) {
                  try {
                    // 1、使用安全控件创建文件
                    let phAccessHelper: photoAccessHelper.PhotoAccessHelper =
                      photoAccessHelper.getPhotoAccessHelper(this.context);
                    let options: photoAccessHelper.CreateOptions = {
                      title: Date.now().toString()
                    };
                    // createAsset的调用需要ohos.permission.READ_IMAGEVIDEO和ohos.permission.WRITE_IMAGEVIDEO的权限
                    let photoUri: string =
                      await phAccessHelper.createAsset(photoAccessHelper.PhotoType.IMAGE, 'png', options);
                    console.info('CameraDemo createAsset successfully, photoUri: ' + photoUri);
                    let file: fileIo.File = fileIo.openSync(photoUri, fileIo.OpenMode.WRITE_ONLY);
                    fileIo.writeSync(file.fd, this.buffer);
                    fileIo.closeSync(file);
                    promptAction.showToast({ message: `保存成功` })
                  } catch (error) {
                    let err = error as BusinessError;
                    console.error(`CameraDemo savePicture error: ${JSON.stringify(err)}`);
                    promptAction.showToast({ message: `保存失败` })
                  }
                }
              } else {
                console.error('CameraDemo SaveButtonOnClickResult createAsset failed.');
                promptAction.showToast({ message: `保存失败` })
              }
              setTimeout(() => {
                this.hasPicture = false;
                this.finalPixelMap = undefined;
              }, 1000)
            })

        } else {
          XComponent({
            id: '',
            type: 'surface',
            libraryname: '',
            controller: this.mXComponentController
          })
            .onLoad(() => {
              // 设置Surface宽高(1920*1080),预览尺寸设置参考前面 previewProfilesArray 获取的当前设备所支持的预览分辨率大小去设置
              // 预览流与录像输出流的分辨率的宽高比要保持一致
              this.mXComponentController.setXComponentSurfaceSize({ surfaceWidth: 1920, surfaceHeight: 1080 });
              // 获取Surface ID
              this.surfaceId = this.mXComponentController.getXComponentSurfaceId();
              setTimeout(async () => {
                await this.prepareCamera();
              }, 500);
            })
            .width('100%')
            .height(600)

          Button('拍照')
            .width(200)
            .height(30)
            .onClick(async () => {
              let photoCaptureSetting: camera.PhotoCaptureSetting = {
                quality: camera.QualityLevel.QUALITY_LEVEL_HIGH, // 设置图片质量高
                rotation: camera.ImageRotation.ROTATION_0 // 设置图片旋转角度0
              }
              // 1、通过拍照流实现:点击拍照
              await this.photoOutput?.capture(photoCaptureSetting).catch((error: BusinessError) => {
                console.error(`CameraDemo Failed to capture the photo ${error.message}`); //不符合条件则进入
              })

              this.hasPicture = true;
            })
        }
      }
      .width('100%')
      .height('100%')
      .padding(15)
      .borderRadius(8)
    }
    .width('100%')
    .height('100%')
    .backgroundColor('#FFFFFF')
  }

  async prepareCamera() {
    this.createCameraManager();

    if (!this.cameraManager) {
      console.error('CameraDemo cameraManager is undefined.')
      return;
    }

    // 获取支持指定的相机设备对象
    let cameraDevices: Array<camera.CameraDevice> = [];
    try {
      cameraDevices = this.cameraManager.getSupportedCameras();
    } catch (error) {
      let err = error as BusinessError;
      console.error(`CameraDemo The getSupportedCameras call failed. error: ${JSON.stringify(err)}`)
    }

    cameraDevices.forEach((cameraDevice: camera.CameraDevice) => {
      console.info(`CameraDemo cameraId: ${cameraDevice.cameraId}, cameraPosition: ${cameraDevice.cameraPosition.toString()}, cameraType: ${cameraDevice.cameraType.toString()}, connectionType: ${cameraDevice.connectionType.toString()}`)
    })

    // 创建相机输入流
    try {
      this.cameraInput = this.cameraManager.createCameraInput(cameraDevices[0]);
    } catch (error) {
      let err = error as BusinessError;
    }
  }
}
分享
微博
QQ
微信
回复
2天前
相关问题
napi里面,相同输入输出不一致
1684浏览 • 1回复 待解决
HarmonyOS 单位不一致问题
47浏览 • 1回复 待解决
文字空行高度字体高度不一致
2116浏览 • 1回复 待解决
如何创建相机预览输出
140浏览 • 0回复 待解决
签名不一致报错怎么回事?
2713浏览 • 1回复 待解决
water flow 出现gap不一致问题
703浏览 • 1回复 待解决
启动和调试的行为不一致
225浏览 • 1回复 待解决
依赖hsp出包,报错versionname不一致
87浏览 • 1回复 待解决
window 全屏操作不同设备表现不一致
390浏览 • 1回复 待解决
Path组件绘制的线条粗细不一致
1914浏览 • 1回复 待解决