HarmonyOS 自定义相机拍完照后保存图片相关问题

根据demo里面的代码,自定义相机拍完照后直接保存图片,然后将图片路径作为参数在页面跳转时一起传入新的页面。应该如何修改demo的代码?

import { abilityAccessCtrl, PermissionRequestResult, Permissions } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { promptAction, router } from '@kit.ArkUI';
import { image } from '@kit.ImageKit';
import { photoAccessHelper } from '@kit.MediaLibraryKit';
import { fileIo, } from '@kit.CoreFileKit';
import { camera, cameraPicker } from '@kit.CameraKit';
import { picker } from '@kit.CoreFileKit';


const TAG = '[PhotoDemo]';

@Entry
@Component
export struct scanCustomCamera {
  type: cameraPicker.PickerMediaType = cameraPicker.PickerMediaType.PHOTO;
  isVideo: boolean = true;
  path: string = '';
  context: Context = getContext(this) as Context;
  @State hasPicture: boolean = false;
  @State finalPixelMap: image.PixelMap | undefined = undefined;
  // 设置安全控件按钮属性
  @State saveButtonOptions: SaveButtonOptions = {
    icon: SaveIconStyle.FULL_FILLED,
    text: SaveDescription.SAVE_IMAGE,
    buttonType: ButtonType.Capsule
  }
  @State buffer: ArrayBuffer | undefined = undefined;

  // 当buffer更新时触发事件
  onPictureCaptured(buffer: ArrayBuffer) {
    this.buffer = buffer;
    return buffer;
  }

  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}`);
    })
  }

  @State surfaceId: string = '';
  @State imageSize: image.Size = { width: 1920, height: 1080 };
  @State isface: boolean = false;
  @State currentIndex: number = 0;
  @State modeBool: boolean = false;
  private mXComponentController: XComponentController = new XComponentController;
  private cameraManager: camera.CameraManager | undefined = undefined;
  private cameraInput: camera.CameraInput | undefined = undefined;
  private photoOutput: camera.PhotoOutput | undefined = undefined;
  private previewOutput: camera.PreviewOutput | undefined = undefined;
  private cameraSession: camera.PhotoSession | undefined = undefined;

  build() {
    Column() {

      //预览框
      Column({ space: 10 }) {
        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.通过文件管理写入文件
                      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 {
          Stack() {
            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('90%')

            //相机预览界面提示框
            Column() {
              Image(this.finalPixelMap)
              if (this.modeBool) {
                Stack() {
                  Image($r('app.media.promptBorder'))
                    .objectFit(ImageFit.Cover)
                    .height('90%')
                  Image($r(this.isface ? 'app.media.nationalEmblem' : 'app.media.face'))
                    .objectFit(ImageFit.Cover)
                    .height('20%')
                    .translate({
                      //改变坐标系位置
                      x: 90,
                      y: this.isface ? -150 : 150
                    })
                  Button('切换正反面')
                    .height('20')
                    .backgroundColor('rgba(24,36,49,0.1)')
                    .translate({
                      //改变坐标系位置
                      y: 230
                    })
                    .onClick(() => {
                      this.isface = !this.isface
                    })
                }
              } else {
                Image($r('app.media.promptBorder'))
                  .objectFit(ImageFit.Cover)
                  .height('90%')
              }
            }
          }
          .height('80%')

          //底部控制区域
          Row() {
            Image($r('app.media.takePhoto'))//拍照按钮
              .objectFit(ImageFit.Cover)
              .width(50)
              .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;

                  async (result: SaveButtonOnClickResult) => {
                    if (result == SaveButtonOnClickResult.SUCCESS) {
                      if (this.finalPixelMap) {
                        try {
                          let phAccessHelper: photoAccessHelper.PhotoAccessHelper =
                            photoAccessHelper.getPhotoAccessHelper(this.context);
                          let options: photoAccessHelper.CreateOptions = {
                            title: Date.now().toString()
                          };
                          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: `保存成功` });
                          //拍完照后跳转到这个页面
                          router.pushUrl({
                            url: "pages/scan_imageHandle",
                          })
                        } 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);
                  };
                  router.pushUrl({
                    url: "pages/scan_imageHandle",
                    params: { info: this.finalPixelMap }
                  });
                })
          }
          .justifyContent(FlexAlign.SpaceAround)
          .height('50')
          .width('100%')

        }
      }
      .backgroundColor(Color.Black)
      .width('100%')
      .height('100%')
      .padding(10)
      .borderRadius(8)
    }
    .width('100%')
    .height('100%')
    .backgroundColor('#FFFFFF')
  }

  /*
   自定义相机部分,可略过
   */
  // 创建CameraManager对象
  createCameraManager() {
    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}`);
    });
  }

  // 函数中设置监听photoAvailable,在回调中生成图片
  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 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()}`)
    })


    // 获取设备支持的具体某个相机对象的支持的模式类型,包含普通拍照及普通录像两种模式,cameraDevices[0]代表后置相机
    let cameraSceneModes: Array<camera.SceneMode> = [];
    try {
      cameraSceneModes = this.cameraManager.getSupportedSceneModes(cameraDevices[1]);
      cameraSceneModes.forEach((cameraSceneMode: camera.SceneMode) => {
        console.info(`CameraDemo cameraSceneMode: ${cameraSceneMode.toString()}`)
      })
      //判断支持的模式类型是否包含拍照
      let isSupportPhotoMode: boolean = cameraSceneModes.indexOf(camera.SceneMode.NORMAL_PHOTO) >= 0;
      if (!isSupportPhotoMode) {
        console.error('CameraDemo photo mode not support');
        return;
      }
    } catch (error) {
      let err = error as BusinessError;
      console.error(`CameraDemo The getSupportedSceneModes call failed. error: ${JSON.stringify(err)}`)
    }

    // 创建相机输入流
    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[1], (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 cameraOutputCapability: camera.CameraOutputCapability =
      this.cameraManager.getSupportedOutputCapability(cameraDevices[1], camera.SceneMode.NORMAL_PHOTO)
    if (!cameraOutputCapability) {
      console.error('CameraDemo cameraManager.getSupportedOutputCapability error');
      return;
    }

    //获取当前设备支持的预览能力
    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)}`);
    });

    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.createSession(camera.SceneMode.NORMAL_PHOTO) as camera.PhotoSession;
    } 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)}`);
    }

    // 向会话中添加拍照输出流
    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)}`);
    }
  }
}
HarmonyOS
1天前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
shlp

参考示例如下:

import camera from '@ohos.multimedia.camera';
import image from '@ohos.multimedia.image';
import abilityAccessCtrl from '@ohos.abilityAccessCtrl';
import common from '@ohos.app.ability.common';
import fs from '@ohos.file.fs';
import { BusinessError } from '@kit.BasicServicesKit';
import PhotoAccessHelper from '@ohos.file.photoAccessHelper';


@Entry
@Component
struct Index {
  @State message: string = 'Hello World'
  private mXComponentController: XComponentController = new XComponentController;
  private surfaceId: string = '-1';
  @State imgUrl: PixelMap | undefined = undefined;
  private context: ESObject = undefined
  private previewProfilesObj2: camera.Profile | undefined = undefined;
  private receiver: image.ImageReceiver | undefined = undefined;
  @State pixma: PixelMap | undefined = undefined
  @State photoOutput: camera.PhotoOutput | undefined = undefined;

  aboutToAppear() {
    //申请权限
    let context = getContext() as common.UIAbilityContext;
    abilityAccessCtrl.createAtManager().requestPermissionsFromUser(context, ['ohos.permission.CAMERA']).then(() => {
      this.createDualChannelPreview(this.surfaceId);
    });
  }

  onPageShow(): void {
    this.createDualChannelPreview(this.surfaceId);
  }

  async createDualChannelPreview(XComponentSurfaceId: string): Promise<void> {
    let cameraManager = await camera.getCameraManager(getContext() as ESObject);
    let camerasDevices: Array<camera.CameraDevice> = cameraManager.getSupportedCameras(); // 获取支持的相机设备对象

    // 获取profile对象
    let profiles: camera.CameraOutputCapability =
      cameraManager.getSupportedOutputCapability(camerasDevices[0]); // 获取对应相机设备profiles
    let previewProfiles: Array<camera.Profile> = profiles.previewProfiles;
    // 预览流2
    this.previewProfilesObj2 = previewProfiles[0];
    this.receiver =
      image.createImageReceiver(this.previewProfilesObj2.size.width, this.previewProfilesObj2.size.height, 2000, 8);

    // 创建 预览流2 输出对象
    let imageReceiverSurfaceId: string = await this.receiver.getReceivingSurfaceId();
    let previewOutput2: camera.PreviewOutput =
      cameraManager.createPreviewOutput(this.previewProfilesObj2, imageReceiverSurfaceId);
    // 创建拍照输出流
    // let photoOutput: camera.PhotoOutput | undefined = undefined;
    let photoProfilesArray: Array<camera.Profile> = profiles.photoProfiles;
    try {
      this.photoOutput = cameraManager.createPhotoOutput(photoProfilesArray[0]);
    } catch (error) {
      let err = error as BusinessError;
      console.error('Failed to createPhotoOutput errorCode = ' + err.code);
    }
    if (this.photoOutput === undefined) {
      return;
    }
    // 创建cameraInput对象
    let cameraInput: camera.CameraInput = cameraManager.createCameraInput(camerasDevices[0]);
    // 打开相机
    await cameraInput.open();
    // 会话流程
    let captureSession: camera.CaptureSession = cameraManager.createCaptureSession();
    // 开始配置会话
    captureSession.beginConfig();
    // 把CameraInput加入到会话
    captureSession.addInput(cameraInput);
    // 把 预览流2 加入到会话
    captureSession.addOutput(previewOutput2);

    try {
      captureSession.addOutput(this.photoOutput);
    } catch (error) {
      let err = error as BusinessError;
      console.error('Failed to addOutput(photoOutput). errorCode = ' + err.code);
    }
    // 提交配置信息
    await captureSession.commitConfig();
    // 会话开始
    await captureSession.start();
    this.onImageArrival(this.receiver);
    this.setPhotoOutputCb(this.photoOutput)

  }

  async savePicture(buffer: ArrayBuffer, img: image.Image) {
    const context = getContext(this);
    let photoAccessHelper: PhotoAccessHelper.PhotoAccessHelper = PhotoAccessHelper.getPhotoAccessHelper(context);
    let options: PhotoAccessHelper.CreateOptions = {
      title: Date.now().toString()
    };
    let photoUri: string = await photoAccessHelper.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();
  }

  setPhotoOutputCb(photoOutput: camera.PhotoOutput) {
    //设置回调之后,调用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;
          if (component.byteBuffer as ArrayBuffer) {
            let sourceOptions: image.SourceOptions = {
              sourceDensity: 120,
              sourcePixelFormat: 0, // NV21
              sourceSize: {
                height: 240,
                width: 320
              },
            }
            try {
              let imageResource = image.createImageSource(component.byteBuffer, sourceOptions);
              imageResource.createPixelMap({}).then((res) => {
                this.pixma = res;
              });
            } catch (error) {
              let err = error as BusinessError;
              console.error('Failed to addOutput(photoOutput). errorCode = ' + err.code);
            }
          } else {
            return;
          }

        } else {
          console.error('byteBuffer is null');
          return;
        }
        this.savePicture(buffer, imageObj);

      });
    });
  }

  async onImageArrival(receiver: image.ImageReceiver): Promise<void> {
    receiver.on('imageArrival', () => {
      console.error("imageArrival callback");
      receiver.readLatestImage((err, nextImage: image.Image) => {
        if (err || nextImage === undefined) {
          return;
        }
        nextImage.getComponent(image.ComponentType.JPEG, async (err, imgComponent: image.Component) => {
          if (err || imgComponent === undefined) {
            return;
          }
          this.saveImageToFile(imgComponent.byteBuffer);
          if (imgComponent.byteBuffer as ArrayBuffer) {
            let sourceOptions: image.SourceOptions = {
              sourceDensity: 120,
              sourcePixelFormat: 8, // NV21
              sourceSize: {
                height: this.previewProfilesObj2!.size.height,
                width: this.previewProfilesObj2!.size.width
              },
            }
            let imageResource = image.createImageSource(imgComponent.byteBuffer, sourceOptions);
            let decodingOptions: image.DecodingOptions = {
              editable: true,
              desiredPixelFormat: 3,

            }
            imageResource.createPixelMap(decodingOptions).then((res) => {
              this.imgUrl = res;
            });
          } else {
            return;
          }
          nextImage.release();
        })
      })
    })
  }

  saveImageToFile(data: ArrayBuffer) {
    const context = getContext(this);
    let filePath = context.tempDir + "/test.jpg";
    console.info("path is " + filePath);
    let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
    fs.write(file.fd, data, (err, writeLen) => {
      if (err) {
        console.info("write failed with error message: " + err.message + ", error code: " + err.code);
      } else {
        console.info("write data to file succeed and size is:" + writeLen);
        fs.closeSync(file);
      }
    });
  }
}
分享
微博
QQ
微信
回复
1天前
相关问题
HarmonyOS 自定义相机预览问题
35浏览 • 1回复 待解决
HarmonyOS 自定义dialog相关问题
0浏览 • 1回复 待解决
HarmonyOS 自定义相机拍照数据展示
817浏览 • 1回复 待解决
自定义弹窗使用相关问题
972浏览 • 1回复 待解决
HarmonyOS 自定义相机demo
349浏览 • 1回复 待解决
HarmonyOS 如何自定义相机
26浏览 • 1回复 待解决
HarmonyOS 关于自定义相机功能
24浏览 • 1回复 待解决
HarmonyOS 如何自定义相机背景
21浏览 • 1回复 待解决
HarmonyOS 自定义相机演示demo
246浏览 • 1回复 待解决
HarmonyOS 自定义相机拍照不成功
19浏览 • 1回复 待解决
HarmonyOS 使用自定义相机左边有间距
26浏览 • 1回复 待解决
能够提供HarmonyOS自定义相机案例吗?
346浏览 • 1回复 待解决
HarmonyOS 自定义图片选择界面
47浏览 • 1回复 待解决
HarmonyOS 自定义相机前置摄像头变形
33浏览 • 1回复 待解决