HarmonyOS鸿蒙Next中摄像头预览流图片格式转换

HarmonyOS鸿蒙Next中摄像头预览流图片格式转换 最近在做摄像头预览的功能,需要处理预览的帧图片,大家都知道Camera输出的图像格式是NV21的,这种情况就需要转换成BGRA或者RGBA来使用,比较简单,直接分享代码吧

  1. 首先需要通过ImageReceiver的on(‘imageArrival’)监听数据流,然后通过调用readNextImage方法获取到原始数据流(NV21)
let mReceiver = image.createImageReceiver(
  this.previewProfile.size.width,
  this.previewProfile.size.height,
  2000,
  8);
let mSurfaceId = await mReceiver.getReceivingSurfaceId();
this.cameraOutput = this.cameraManager.createPreviewOutput(this.previewProfile, mSurfaceId);
this.captureSession.addOutput(this.cameraOutput);
mReceiver.on('imageArrival', async () => {
  mReceiver.readNextImage().then(async imageData => {
    let imageComponent = await imageData.getComponent(4); // 参数只能是4
    let imageBuffer = imageComponent.byteBuffer; // NV21格式的imageBuffer
    imageData.release();
  })
})
  1. NV21转换成BGRA,组建Image就可以直接使用了
let sourceOptions = {
  sourceDensity: 120,
  sourcePixelFormat: 8, // NV21
  sourceSize: {
    height: 480,
    width: 640
  }
}
// 转换成BGRA格式的imageResource
let imageResource = image.createImageSource(imageBuffer, sourceOptions);

// 创建pixelMap

imageResource.createPixelMap

到此转换 就结束了,仅供参考~~


更多关于HarmonyOS鸿蒙Next中摄像头预览流图片格式转换的实战教程也可以访问 https://www.itying.com/category-93-b0.html

3 回复

大佬好,我在做拍照时,拍照的数据无法转为 Image() 控件,你们有遇到这个问题么。

更多关于HarmonyOS鸿蒙Next中摄像头预览流图片格式转换的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS鸿蒙Next中,摄像头预览流的图片格式转换可以通过CameraKitImage模块实现。CameraKit用于获取摄像头预览流,Image模块用于处理图像数据。预览流通常以YUV格式输出,可以通过Image模块将其转换为RGBJPEG格式。

具体步骤如下:

  1. 使用CameraKit初始化摄像头并获取预览流。
  2. 通过Image模块的PixelMap类处理YUV数据。
  3. 调用PixelMapcreatePixelMap方法将YUV数据转换为RGB格式。
  4. 若需转换为JPEG格式,可使用ImagePacker类将PixelMap对象编码为JPEG

代码示例:

import camera from '@ohos.camera';
import image from '@ohos.multimedia.image';

// 初始化摄像头
let cameraKit = camera.getCameraKit();
let cameraInput = cameraKit.createCameraInput(camera.CameraId.BACK);

// 获取预览流
let previewOutput = cameraKit.createPreviewOutput();
cameraKit.session.addOutput(previewOutput);

// 处理YUV数据
previewOutput.on('frameArrival', (frame) => {
    let imageSource = image.createImageSource(frame);
    let pixelMap = imageSource.createPixelMap();

    // 转换为RGB格式
    let rgbPixelMap = image.createPixelMap(pixelMap, { format: image.PixelMapFormat.RGB_888 });

    // 转换为JPEG格式
    let imagePacker = image.createImagePacker();
    imagePacker.packing(rgbPixelMap, { format: 'image/jpeg' }).then((data) => {
        // 处理JPEG数据
    });
});

在HarmonyOS鸿蒙Next中,摄像头预览流的图片格式转换可以通过CameraKit API实现。首先,使用CameraKit获取摄像头预览流数据,通常为YUV格式。然后,通过Image类进行格式转换,如将YUV转换为RGBJPEG。具体步骤包括:

  1. 初始化CameraKit并配置摄像头参数;
  2. 获取预览流数据;
  3. 使用Image类进行格式转换;
  4. 处理转换后的图像数据。

确保在config.json中声明摄像头权限。

回到顶部