HarmonyOS 鸿蒙Next相机预览demo

发布于 1周前 作者 nodeper 来自 鸿蒙OS

HarmonyOS 鸿蒙Next相机预览demo 需要相机预览demo

2 回复

可以参考这个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]';
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();
  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({
    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;
    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);
    this.onImageArrival(this.imageReceiver);
  } catch (error) {
    let err = error as BusinessError;
    console.error(CameraDemo createImageReceiver error ${JSON.stringify(err)});
    return
  }
  //创建拍照输出流
  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();
    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)});
  }
  //向会话中添加拍照输出流
  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)
}

更多关于HarmonyOS 鸿蒙Next相机预览demo的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


针对“HarmonyOS 鸿蒙Next相机预览demo”的问题,以下是一个简洁且专业的回答:

HarmonyOS 鸿蒙Next相机预览demo通常涉及使用鸿蒙系统提供的API来实现相机预览功能。为了创建这样的demo,你需要了解鸿蒙系统的相机服务框架以及相关的组件和接口。

在鸿蒙系统中,相机预览功能通常通过CameraKit组件来实现。你需要先在你的项目中引入CameraKit相关的库,并配置必要的权限。然后,你可以使用CameraCaptureSession来启动相机预览。在这个过程中,你需要设置预览的Surface,通常是通过SurfaceProvider来获取。

此外,为了处理相机的生命周期和状态变化,你需要实现相应的监听器,并在适当的时候启动、停止或重新配置相机预览。

在编写demo时,你还可以利用鸿蒙系统的布局和UI组件来创建一个友好的用户界面,用于控制相机的启动、停止以及切换前后摄像头等功能。

请注意,由于鸿蒙系统的不断更新和变化,具体的API和实现方式可能会有所不同。因此,在开发过程中,建议参考最新的鸿蒙系统文档和开发者指南。

如果问题依旧没法解决请联系官网客服,官网地址是:https://www.itying.com/category-93-b0.html

回到顶部