HarmonyOS 自定义相机,跳转至图库应用后再返回,自定义相机预览黑屏

自定义相机,跳转至图库应用后再返回,自定义相机预览黑屏,或者从后台再返回自定义相机页面的时候,也会出现预览黑屏的问题。

page页面:

async XComponentInit() {
  this.XComponentController.setXComponentSurfaceSize({ surfaceWidth: 240, surfaceHeight: 320 });
  this.surfaceId = this.XComponentController.getXComponentSurfaceId();
  await this.camera.initCamera(this.surfaceId);
}

aboutToAppear(): void {
  this.XComponentInit();
}

onPageShow() {
  this.XComponentInit();
}

onPageHide() {
  this.camera.releaseCamera();
}

async aboutToDisappear() {
  await this.camera.releaseCamera();
}

相机工具类页面:

import { photoAccessHelper } from '@kit.MediaLibraryKit';
import { fileIo } from '@kit.CoreFileKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { camera } from '@kit.CameraKit';
import { common } from '@kit.AbilityKit';
import { image } from '@kit.ImageKit';
import { buffer } from '@kit.ArkTS';

export class CameraPhotoUtils {
  private cameraManager?: camera.CameraManager
  private cameraInput?: camera.CameraInput
  public previewOutput?: camera.PreviewOutput
  public photoOutput?: camera.PhotoOutput
  private photoSession?: camera.PhotoSession
  private receiver: image.ImageReceiver | undefined = undefined;
  base64Src: string = '';
  private pixelMap?: image.PixelMap
  private photoUri: string = ''

  async initCamera(surfaceId: string): Promise<void> {
    this.cameraManager = camera.getCameraManager(getContext(this) as common.UIAbilityContext);
    let cameraArray: Array<camera.CameraDevice> = this.cameraManager.getSupportedCameras();
    let cameraDevice = cameraArray[0];
    this.cameraInput = this.cameraManager.createCameraInput(cameraDevice);
    await this.cameraInput.open();
    let cameraOutputCap: camera.CameraOutputCapability =
      this.cameraManager!.getSupportedOutputCapability(cameraDevice, camera.SceneMode.NORMAL_PHOTO);
    let previewProfilesArray: Array<camera.Profile> = cameraOutputCap.previewProfiles;
    let photoProfilesArray: Array<camera.Profile> = cameraOutputCap.photoProfiles;
    this.previewOutput = this.cameraManager!.createPreviewOutput(previewProfilesArray[5], surfaceId);
    let size: image.Size = {
      height: 2592, width: 1200
    };
    this.receiver = image.createImageReceiver(size, image.ImageFormat.JPEG, 8);
    this.photoOutput = this.cameraManager!.createPhotoOutput(photoProfilesArray[5]);
    this.photoOutput.on('photoAvailable', (errCode: BusinessError, photo: camera.Photo): void => {
      let imageObj = photo.main;
      imageObj.getComponent(image.ComponentType.JPEG, async (errCode: BusinessError, component: image.Component) => {
        if (errCode || component === undefined) {
          return;
        }
        let mBuffer: ArrayBuffer;
        mBuffer = component.byteBuffer;
        console.info(JSON.stringify(mBuffer));
        await this.savePicture(mBuffer);
      })
      imageObj.release();
    })
    this.photoSession = this.cameraManager!.createSession(camera.SceneMode.NORMAL_PHOTO);
    this.photoSession.beginConfig();
    this.photoSession.addInput(this.cameraInput);
    this.photoSession.addOutput(this.previewOutput);
    this.photoSession.addOutput(this.photoOutput);
    await this.photoSession.commitConfig();
    await this.photoSession.start();
    this.photoSession.on('error', (error: BusinessError) => {
      console.error(`Photo session error code: ${error.code}`);
    });
  }

  async takePicture() {
    console.log('takePicture');
    this.photoOutput!.capture();
  }

  async savePicture(mBuffer: ArrayBuffer): Promise<void> {
    let photoHelper: photoAccessHelper.PhotoAccessHelper =
      photoAccessHelper.getPhotoAccessHelper(getContext(this) as common.UIAbilityContext);
    let options: photoAccessHelper.CreateOptions = {
      title: Date.now().toString()
    };
    //createAsset的调用需要ohos.permission.READ_IMAGEVIDEO和ohos.permission.WRITE_IMAGEVIDEO的权限
    this.photoUri = await photoHelper.createAsset(photoAccessHelper.PhotoType.IMAGE, 'jpg', options);
    console.info(this.photoUri);
    // 创建图片资源
    const imageSource: image.ImageSource = image.createImageSource(mBuffer);
    let decodingOptions: image.DecodingOptions = {
      editable: true,
      // desiredPixelFormat: 3,
    }
    // 创建pixelMap
    this.pixelMap = await imageSource.createPixelMap(decodingOptions)
    this.pixelMap.crop({ x: 32, y: 400, size: { height: 200, width: 375 } });

    let file: fileIo.File = fileIo.openSync(this.photoUri, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE);
    // await fileIo.write(file.fd, mBuffer);

    // pixelMap 转 base64
    const imagePackerApi = image.createImagePacker();
    let packOpts: image.PackingOption = { format: "image/jpeg", quality: 100 };
    imagePackerApi.packing(this.pixelMap, packOpts).then((data: ArrayBuffer) => {
      // data 为打包获取到的文件流,写入文件保存即可得到一张图片
      if (data) {
        let buf: buffer.Buffer = buffer.from(data);
        this.base64Src = 'data:image/jpeg;base64,' + buf.toString('base64', 0, buf.length);
        console.info('base64Src: ' + this.base64Src);
        console.info('Succeeded in packing the image.');
      }
    }).catch((error: BusinessError) => {
      console.error('Failed to pack the image. And the error is: ' + error);
    })

    this.pixelMap.release()
    imagePackerApi.release()
    fileIo.closeSync(file);
  }

  async releaseCamera(): Promise<void> {
    if (this.cameraInput) {
      await this.cameraInput.close();
    }
    if (this.previewOutput) {
      await this.previewOutput.release();
    }
    if (this.photoOutput) {
      await this.photoOutput.release()
    }
    if (this.photoSession) {
      await this.photoSession.release();
      this.photoSession = undefined;
    }
  }
}
HarmonyOS
1天前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
zxjiu

参考以下demo:

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, router } from '@kit.ArkUI';
import { fileIo } from '@kit.CoreFileKit';

const TAG = '[CameraDemo]';

@Entry
@Component
export 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 previewOutput2: 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}`);
    })
  }

  async onPageShow() {
    await this.prepareCamera();
  }

  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() {
      Flex({ direction: FlexDirection.Row, justifyContent: FlexAlign.Start }) {
        Image($r('app.media.ic_public_back'))
          .width(30)
          .onClick(() => {
            router.back()
          })
      }

      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);
                    // 2.1、方式一:通过文件管理写入文件
                    let file: fileIo.File = fileIo.openSync(photoUri, fileIo.OpenMode.WRITE_ONLY);
                    fileIo.writeSync(file.fd, this.buffer);
                    fileIo.closeSync(file);
                    // 2.2、方式二:通过imagePacker写入文件
                    // let file: fileIo.File = fileIo.openSync(photoUri, fileIo.OpenMode.WRITE_ONLY);
                    // let imagePacker: image.ImagePacker = image.createImagePacker();
                    // let packOpts: image.PackingOption = { format: 'image/jpeg', quality: 100 };
                    // await imagePacker.packToFile(this.finalPixelMap, file.fd, packOpts);
                    // 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 * 1.3,
                surfaceHeight: 1080 * 1.3
              });
              // 获取Surface ID
              this.surfaceId = this.mXComponentController.getXComponentSurfaceId();
              setTimeout(async () => {
                await this.prepareCamera();
              }, 500);
            })
            .width('100%')
            .height(300)

          // 双路预览
          Image(this.pixelMap)
            .objectFit(ImageFit.Fill)
            .width('100%')
            .height(300)

          Button('拍照')
            .width(200)
            .height(30)
            .onClick(async () => {
              let photoCaptureSetting: camera.PhotoCaptureSetting = {
                quality: camera.QualityLevel.QUALITY_LEVEL_HIGH, // 设置图片质量高
                rotation: camera.ImageRotation.ROTATION_0, // 设置图片旋转角度0
                // mirror: true// 镜像
              }
              // 1、通过拍照流实现:点击拍照
              await this.photoOutput?.capture(photoCaptureSetting).catch((error: BusinessError) => {
                console.error(`CameraDemo Failed to capture the photo ${error.message}`); //不符合条件则进入
              })
              // 2、从imageReceiver中获取图片,实现拍照
              // this.finalPixelMap = this.pixelMap;
              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;
      console.error(`CameraDemo createCaptureSession error. error: ${JSON.stringify(err)}`);
      return
    }
    // 监听cameraInput错误信息
    this.cameraInput.on('error', cameraDevices[0], (error: BusinessError) => {
      console.error(`CameraDemo Camera input error: ${JSON.stringify(error)}`);
    });

    // 打开相机
    try {
      await this.cameraInput.open();
    } catch (error) {
      let err = error as BusinessError;
      console.error(`CameraDemo cameraInput open error. error: ${JSON.stringify(err)}`);
    }

    // 获取指定的相机设备对象支持的模式
    let cameraSceneModes: Array<camera.SceneMode> = [];
    try {
      cameraSceneModes = this.cameraManager.getSupportedSceneModes(cameraDevices[0]);
      cameraSceneModes.forEach((cameraSceneMode: camera.SceneMode) => {
        console.info(`CameraDemo cameraSceneMode: ${cameraSceneMode.toString()}`)
      })
    } catch (error) {
      let err = error as BusinessError;
      console.error(`CameraDemo The getSupportedSceneModes call failed. error: ${JSON.stringify(err)}`)
    }

    // 获取相机设备支持的输出流能力
    let cameraOutputCapability: camera.CameraOutputCapability =
      this.cameraManager.getSupportedOutputCapability(cameraDevices[0], camera.SceneMode.NORMAL_PHOTO)
    if (!cameraOutputCapability) {
      console.error('CameraDemo cameraManager.getSupportedOutputCapability error');
      return;
    }
    this.printCameraOutputCapability(cameraOutputCapability);
    let previewProfile = cameraOutputCapability.previewProfiles[0];
    cameraOutputCapability.previewProfiles.forEach((profile) => {
      if (profile.size.width == this.imageSize.width && profile.size.height == this.imageSize.height) {
        previewProfile = profile;
        return;
      }
    })
    this.imageSize = previewProfile.size;

    // 创建相机预览输出流
    try {
      this.previewOutput = this.cameraManager.createPreviewOutput(previewProfile, this.surfaceId);
    } catch (error) {
      let err = error as BusinessError;
      console.error(`CameraDemo createCaptureSession error. error: ${JSON.stringify(err)}`);
      return
    }
    // 监听previewOutput错误信息
    this.previewOutput.on('error', (error: BusinessError) => {
      console.error(`CameraDemo previewOutput error: ${JSON.stringify(error)}`);
    });

    //双路预览: 创建 预览流2 输出对象
    try {
      this.imageReceiver = image.createImageReceiver(this.imageSize, image.ImageFormat.JPEG, 8);
      let imageReceiverSurfaceId: string = await this.imageReceiver.getReceivingSurfaceId();
      this.previewOutput2 = this.cameraManager.createPreviewOutput(previewProfile, imageReceiverSurfaceId);
      this.onImageArrival(this.imageReceiver);
    } catch (error) {
      let err = error as BusinessError;
      console.error(`CameraDemo createImageReceiver error ${JSON.stringify(err)}`);
      return
    }
    // 监听previewOutput2错误信息
    this.previewOutput2.on('error', (error: BusinessError) => {
      console.error(`CameraDemo previewOutput2 error: ${JSON.stringify(error)}`);
    });

    // 创建拍照输出流
    try {
      let photoProfile = cameraOutputCapability.photoProfiles[0];
      cameraOutputCapability.photoProfiles.forEach((profile) => {
        if (profile.size.width == this.imageSize.width && profile.size.height == this.imageSize.height) {
          photoProfile = profile;
          return;
        }
      })
      this.photoOutput = this.cameraManager.createPhotoOutput(photoProfile);
    } catch (error) {
      let err = error as BusinessError;
      console.error(`CameraDemo createPhotoOutput error ${JSON.stringify(err)}`);
    }
    if (this.photoOutput === undefined) {
      console.error('CameraDemo photoOutput is undefined.');
      return;
    }

    //调用上面的回调函数来保存图片
    this.setPhotoOutputCb(this.photoOutput);
    // 创建相机会话
    try {
      // this.cameraSession = this.cameraManager.createCaptureSession();
      this.cameraSession = this.cameraManager.createSession<camera.PhotoSession>(camera.SceneMode.NORMAL_PHOTO);
    } catch (error) {
      let err = error as BusinessError;
      console.error(`CameraDemo createCaptureSession error. error: ${JSON.stringify(err)}`);
      return
    }
    // 监听session错误信息
    this.cameraSession.on('error', (error: BusinessError) => {
      console.error(`CameraDemo Capture session error: ${JSON.stringify(error)}`);
    });

    // 开始会话配置
    try {
      this.cameraSession.beginConfig()
    } catch (error) {
      let err = error as BusinessError;
      console.error(`CameraDemo beginConfig error. error: ${JSON.stringify(err)}`);
    }

    // 向会话中添加相机输入流
    try {
      this.cameraSession.addInput(this.cameraInput)
    } catch (error) {
      let err = error as BusinessError;
      console.error(`CameraDemo addInput error. error: ${JSON.stringify(err)}`);
    }

    // 向会话中添加预览输出流
    try {
      this.cameraSession.addOutput(this.previewOutput)
    } catch (error) {
      let err = error as BusinessError;
      console.error(`CameraDemo add previewOutput error. error: ${JSON.stringify(err)}`);
    }

    // 向会话中添加预览输出流2
    try {
      this.cameraSession.addOutput(this.previewOutput2)
    } catch (error) {
      let err = error as BusinessError;
      console.error(`CameraDemo add previewOutput2 error. error: ${JSON.stringify(err)}`);
    }

    // 向会话中添加拍照输出流
    try {
      this.cameraSession.addOutput(this.photoOutput);
    } catch (error) {
      let err = error as BusinessError;
      console.error(`CameraDemo add photoOutput error. error: ${JSON.stringify(err)}`);
    }

    // 提交会话配置
    try {
      await this.cameraSession.commitConfig();
    } catch (error) {
      let err = error as BusinessError;
      console.error(`CameraDemo captureSession commitConfig error: ${JSON.stringify(err)}`);
    }

    // 启动会话
    try {
      await this.cameraSession.start();
    } catch (error) {
      let err = error as BusinessError;
      console.error(`CameraDemo captureSession start error: ${JSON.stringify(err)}`);
    }

    // 配置相机的参数可以调整拍照的一些功能,包括闪光灯、变焦、焦距等。
    this.configuringSession(this.cameraSession)
  }

  configuringSession(photoSession: camera.PhotoSession): void {
    // 判断设备是否支持闪光灯
    let flashStatus: boolean = false;
    try {
      flashStatus = photoSession.hasFlash();
    } catch (error) {
      let err = error as BusinessError;
      console.error(`CameraDemo Failed to hasFlash. error: ${JSON.stringify(err)}`);
    }
    console.info(`CameraDemo 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(`CameraDemo Failed to check whether the flash mode is supported. error: ${JSON.stringify(err)}`);
      }
      if (flashModeStatus) {
        // 设置自动闪光灯模式
        try {
          photoSession.setFlashMode(camera.FlashMode.FLASH_MODE_AUTO);
        } catch (error) {
          let err = error as BusinessError;
          console.error(`CameraDemo Failed to set the flash mode. error: ${JSON.stringify(err)}`);
        }
      }
    }
    // 判断是否支持连续自动变焦模式
    let focusModeStatus: boolean = false;
    try {
      let status: boolean = photoSession.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO);
      focusModeStatus = status;
    } catch (error) {
      let err = error as BusinessError;
      console.error(`CameraDemo Failed to check whether the focus mode is supported. error: ${JSON.stringify(err)}`);
    }
    if (focusModeStatus) {
      // 设置连续自动变焦模式
      try {
        photoSession.setFocusMode(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO);
      } catch (error) {
        let err = error as BusinessError;
        console.error(`CameraDemo Failed to set the focus mode. error: ${JSON.stringify(err)}`);
      }
    }
    // 获取相机支持的可变焦距比范围
    let zoomRatioRange: Array<number> = [];
    try {
      zoomRatioRange = photoSession.getZoomRatioRange();
    } catch (error) {
      let err = error as BusinessError;
      console.error(`CameraDemo Failed to get the zoom ratio range. error: ${JSON.stringify(err)}`);
    }
    if (zoomRatioRange.length <= 0) {
      return;
    }
    // 设置可变焦距比
    try {
      photoSession.setZoomRatio(zoomRatioRange[0]);
    } catch (error) {
      let err = error as BusinessError;
      console.error(`CameraDemo Failed to set the zoom ratio value. error: ${JSON.stringify(err)}`);
    }
  }

  // 通过Surface进行数据传递,通过ImageReceiver的surface获取预览图像。
  async onImageArrival(receiver: image.ImageReceiver): Promise<void> {
    receiver.on('imageArrival', () => {
      receiver.readNextImage(async (err, nextImage: image.Image) => {
        console.info(`enter CameraDemo imageArrival, nextImage: ${JSON.stringify(nextImage)}`)
        if (err || nextImage === undefined) {
          console.error(`CameraDemo imageArrival error, error is ${JSON.stringify(err)} or nextImage is undefined`)
          return;
        }
        nextImage.getComponent(image.ComponentType.JPEG, async (err, imgComponent: image.Component) => {
          if (err || imgComponent === undefined) {
            console.error(`CameraDemo getComponent error, error is ${JSON.stringify(err)} or imgComponent is undefined`)
            return;
          }
          if (imgComponent.byteBuffer as ArrayBuffer) {
            let sourceOptions: image.SourceOptions = {
              sourceDensity: 0,
              sourcePixelFormat: image.PixelMapFormat.NV21, // NV21
              sourceSize: this.imageSize
            }
            let imageSource: image.ImageSource = image.createImageSource(imgComponent.byteBuffer, sourceOptions);
            let opts: image.InitializationOptions = {
              editable: false,
              pixelFormat: image.PixelMapFormat.NV21,
              size: this.imageSize
            }
            let pixelMap = await imageSource.createPixelMap(opts);
            await pixelMap.rotate(90.0);
            this.pixelMap = pixelMap;
            await imageSource.release();
          } else {
            return;
          }
          nextImage.release()
        })
      })
    })
  }

  setPhotoOutputCb(photoOutput: camera.PhotoOutput) {
    //设置回调之后,调用photoOutput的capture方法,就会将拍照的buffer回传到回调中
    photoOutput.on('photoAvailable', (errCode: BusinessError, photo: camera.Photo): void => {
      console.info(`CameraDemo getPhoto start. err: ${JSON.stringify(errCode)}`);
      if (errCode || photo === undefined || photo.main === undefined) {
        console.error('CameraDemo getPhoto failed');
        return;
      }
      let imageObj = photo.main;
      imageObj.getComponent(image.ComponentType.JPEG,
        async (errCode: BusinessError, component: image.Component): Promise<void> => {
          console.info('CameraDemo getComponent start');
          if (errCode || component === undefined) {
            console.error('CameraDemo getComponent failed');
            return;
          }
          let buffer: ArrayBuffer;
          if (component.byteBuffer) {
            buffer = component.byteBuffer;
            this.buffer = buffer;
            let sourceOptions: image.SourceOptions = {
              sourceDensity: 0, // 在不确定当前密度时传0
              sourcePixelFormat: image.PixelMapFormat.RGBA_8888,
              sourceSize: this.imageSize
            }
            let imageSource: image.ImageSource = image.createImageSource(buffer, sourceOptions);
            let opts: image.InitializationOptions = {
              editable: false,
              pixelFormat: image.PixelMapFormat.RGBA_8888,
              size: this.imageSize
            }
            let pixelMap = await imageSource.createPixelMap(opts);
            this.finalPixelMap = pixelMap;
          } else {
            console.error('CameraDemo byteBuffer is null');
            return;
          }
        });
    });
  }

  async copyPixelMap(imagePixel: PixelMap): Promise<image.PixelMap> {
    let imageInfo: image.ImageInfo = await imagePixel.getImageInfo();
    console.info(`copyPixelMapSize: width:${imageInfo?.size.width} height:${imageInfo?.size.height}`);
    let newRegion: image.Region = {
      size: { height: imageInfo.size.height, width: imageInfo.size.width },
      x: 0,
      y: 0
    }
    let newArea: image.PositionArea = {
      pixels: new ArrayBuffer(imageInfo.size.height * imageInfo.size.width * 4),
      offset: 0,
      stride: imageInfo.stride,
      region: newRegion
    }
    await imagePixel.readPixels(newArea);
    let opts: image.InitializationOptions = { editable: true, pixelFormat: 4, size: imageInfo.size };
    let imagePixelCache = await image.createPixelMap(newArea.pixels, opts);
    return imagePixelCache;
  }

  printCameraOutputCapability(cameraOutputCapability: camera.CameraOutputCapability) {
    let previewProfileArr: Array<camera.Profile> = cameraOutputCapability.previewProfiles;
    let photoProfileArr: Array<camera.Profile> = cameraOutputCapability.photoProfiles;
    let videoProfileArr: Array<camera.VideoProfile> = cameraOutputCapability.videoProfiles;
    let supportedMetadataObjectTypeArr: Array<camera.MetadataObjectType> =
      cameraOutputCapability.supportedMetadataObjectTypes;
    previewProfileArr.forEach((value: camera.Profile, index: number) => {
      console.info(`CameraDemo 支持的预览尺寸: [${value.size.width},${value.size.height}]`);
    })
    photoProfileArr.forEach((value: camera.Profile, index: number) => {
      console.info(`CameraDemo 支持的拍照尺寸: [${value.size.width},${value.size.height}]`);
    })
    videoProfileArr.forEach((value: camera.VideoProfile, index: number) => {
      console.info(`CameraDemo 支持的录像尺寸: [${value.size.width},${value.size.height}], 支持的帧率范围: [${value.frameRateRange.min},${value.frameRateRange.max}]`);
    })
    supportedMetadataObjectTypeArr.forEach((value: camera.MetadataObjectType, index: number) => {
      console.info(`CameraDemo 支持的metadata流类型: ${value}`);
    })
  }
}
分享
微博
QQ
微信
回复
1天前
相关问题
HarmonyOS 自定义相机预览问题
38浏览 • 1回复 待解决
HarmonyOS 自定义相机demo
354浏览 • 1回复 待解决
HarmonyOS 如何自定义相机
29浏览 • 1回复 待解决
HarmonyOS 如何自定义相机背景
21浏览 • 1回复 待解决
HarmonyOS 自定义相机演示demo
246浏览 • 1回复 待解决
HarmonyOS 关于自定义相机功能
28浏览 • 1回复 待解决
HarmonyOS 自定义相机拍照不成功
19浏览 • 1回复 待解决
HarmonyOS 使用自定义相机左边有间距
29浏览 • 1回复 待解决
能够提供HarmonyOS自定义相机案例吗?
346浏览 • 1回复 待解决
HarmonyOS 自定义相机拍照后数据展示
818浏览 • 1回复 待解决
HarmonyOS 自定义相机前置摄像头变形
38浏览 • 1回复 待解决
【求助】自定义相机Camera2焦距异常
8013浏览 • 1回复 待解决
HarmonyOS PDF预览界面自定义
48浏览 • 1回复 待解决
HarmonyOS 自定义CustomDialog 跳转问题
15浏览 • 1回复 待解决
自定义弹窗自定义转场动画
1179浏览 • 1回复 待解决