HarmonyOS鸿蒙Next中摄像头预览流图片格式转换
HarmonyOS鸿蒙Next中摄像头预览流图片格式转换 最近在做摄像头预览的功能,需要处理预览的帧图片,大家都知道Camera输出的图像格式是NV21的,这种情况就需要转换成BGRA或者RGBA来使用,比较简单,直接分享代码吧
- 首先需要通过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();
})
})
- 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中,摄像头预览流的图片格式转换可以通过CameraKit
和Image
模块实现。CameraKit
用于获取摄像头预览流,Image
模块用于处理图像数据。预览流通常以YUV
格式输出,可以通过Image
模块将其转换为RGB
或JPEG
格式。
具体步骤如下:
- 使用
CameraKit
初始化摄像头并获取预览流。 - 通过
Image
模块的PixelMap
类处理YUV
数据。 - 调用
PixelMap
的createPixelMap
方法将YUV
数据转换为RGB
格式。 - 若需转换为
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
转换为RGB
或JPEG
。具体步骤包括:
- 初始化
CameraKit
并配置摄像头参数; - 获取预览流数据;
- 使用
Image
类进行格式转换; - 处理转换后的图像数据。
确保在config.json
中声明摄像头权限。