1# 双路预览(ArkTS) 2 3在开发相机应用时,需要先参考开发准备[申请相关权限](camera-preparation.md)。 4 5双路预览,即应用可同时使用两路预览流,一路用于在屏幕上显示,一路用于图像处理等其他操作,提升处理效率。 6 7相机应用通过控制相机,实现图像显示(预览)、照片保存(拍照)、视频录制(录像)等基础操作。相机开发模型为Surface模型,即应用通过Surface进行数据传递,通过ImageReceiver的surface获取拍照流的数据、通过XComponent的surface获取预览流的数据。 8 9如果要实现双路预览,即将拍照流改为预览流,将拍照流中的surface改为预览流的surface,通过ImageReceiver的surface创建previewOutput,其余流程与拍照流和预览流一致。 10 11详细的API说明请参考[Camera API参考](../../reference/apis-camera-kit/js-apis-camera.md)。 12 13## 约束与限制 14 15- 暂不支持动态添加流,即不能在没有调用[session.stop](../../reference/apis-camera-kit/js-apis-camera.md#stop11)的情况下,调用[addOutput](../../reference/apis-camera-kit/js-apis-camera.md#addoutput11)添加流。 16- 对ImageReceiver组件获取到的图像数据处理后,需要将对应的图像Buffer释放,确保Surface的BufferQueue正常轮转。 17 18## 调用流程 19 20双路方案调用流程图建议如下: 21 22 23 24## 开发步骤 25 26- 用于处理图像的第一路预览流:创建ImageReceiver对象,获取SurfaceId创建第一路预览流,注册图像监听,按需处理预览流每帧图像。 27- 用于显示画面的第二路预览流:创建XComponent组件,获取SurfaceId创建第二路预览流,预览流画面直接在组件内渲染。 28- 创建预览流获取数据:创建上述两路预览流,配置进相机会话,启动会话后,两路预览流同时获取数据。 29 30### 用于处理图像的第一路预览流 31 321. 获取第一路预览流SurfaceId:创建ImageReceiver对象,通过ImageReceiver对象可获取其SurfaceId。 33 34 ```ts 35 import { image } from '@kit.ImageKit'; 36 imageWidth: number = 1920; // 请使用设备支持profile的size的宽 37 imageHeight: number = 1080; // 请使用设备支持profile的size的高 38 39 async function initImageReceiver():Promise<void>{ 40 // 创建ImageReceiver对象 41 let size: image.Size = { width: this.imageWidth, height: this.imageHeight }; 42 let imageReceiver = image.createImageReceiver(size, image.ImageFormat.JPEG, 8); 43 // 获取取第一路流SurfaceId 44 let imageReceiverSurfaceId = await imageReceiver.getReceivingSurfaceId(); 45 console.info(`initImageReceiver imageReceiverSurfaceId:${imageReceiverSurfaceId}`); 46 } 47 ``` 48 492. 注册监听处理预览流每帧图像数据:通过ImageReceiver组件中imageArrival事件监听获取底层返回的图像数据,详细的API说明请参考[Image API参考](../../reference/apis-image-kit/js-apis-image.md)。 50 51 ```ts 52 import { BusinessError } from '@kit.BasicServicesKit'; 53 import { image } from '@kit.ImageKit'; 54 55 function onImageArrival(receiver: image.ImageReceiver): void { 56 // 注册imageArrival监听 57 receiver.on('imageArrival', () => { 58 // 获取图像 59 receiver.readNextImage((err: BusinessError, nextImage: image.Image) => { 60 if (err || nextImage === undefined) { 61 console.error('readNextImage failed'); 62 return; 63 } 64 // 解析图像内容 65 nextImage.getComponent(image.ComponentType.JPEG, async (err: BusinessError, imgComponent: image.Component) => { 66 if (err || imgComponent === undefined) { 67 console.error('getComponent failed'); 68 } 69 if (imgComponent.byteBuffer) { 70 // 详情见下方解析图片buffer数据参考,本示例以方式一为例 71 let width = nextImage.size.width; // 获取图片的宽 72 let height = nextImage.size.height; // 获取图片的高 73 let stride = imgComponent.rowStride; // 获取图片的stride 74 console.debug(`getComponent with width:${width} height:${height} stride:${stride}`); 75 // stride与width一致 76 if (stride == width) { 77 let pixelMap = await image.createPixelMap(imgComponent.byteBuffer, { 78 size: { height: height, width: width }, 79 srcPixelFormat: 8, 80 }) 81 } else { 82 // stride与width不一致 83 const dstBufferSize = width * height * 1.5 84 const dstArr = new Uint8Array(dstBufferSize) 85 for (let j = 0; j < height * 1.5; j++) { 86 const srcBuf = new Uint8Array(imgComponent.byteBuffer, j * stride, width) 87 dstArr.set(srcBuf, j * width) 88 } 89 let pixelMap = await image.createPixelMap(dstArr.buffer, { 90 size: { height: height, width: width }, 91 srcPixelFormat: 8, 92 }) 93 } 94 } else { 95 console.error('byteBuffer is null'); 96 } 97 // 确保当前buffer没有在使用的情况下,可进行资源释放 98 // 如果对buffer进行异步操作,需要在异步操作结束后再释放该资源(nextImage.release()) 99 nextImage.release(); 100 }) 101 }) 102 }) 103 } 104 ``` 105 106 通过 [image.Component](../../reference/apis-image-kit/js-apis-image.md#component9) 解析图片buffer数据参考: 107 108 > **注意:** 109 > 需要确认图像的宽width是否与行距rowStride一致,如果不一致可参考以下方式处理: 110 111 方式一:去除imgComponent.byteBuffer中stride数据,拷贝得到新的buffer,调用不支持stride的接口处理buffer。 112 113 ```ts 114 // 以NV21为例(YUV_420_SP格式的图片)YUV_420_SP内存计算公式:长x宽+(长x宽)/2 115 const dstBufferSize = width * height * 1.5; 116 const dstArr = new Uint8Array(dstBufferSize); 117 // 逐行读取buffer数据 118 for (let j = 0; j < height * 1.5; j++) { 119 // imgComponent.byteBuffer的每行数据拷贝前width个字节到dstArr中 120 const srcBuf = new Uint8Array(imgComponent.byteBuffer, j * stride, width); 121 dstArr.set(srcBuf, j * width); 122 } 123 let pixelMap = await image.createPixelMap(dstArr.buffer, { 124 size: { height: height, width: width }, srcPixelFormat: 8 125 }); 126 ``` 127 128 方式二:根据stride*height创建pixelMap,然后调用pixelMap的cropSync方法裁剪掉多余的像素。 129 130 ```ts 131 // 创建pixelMap,width宽传行距stride的值 132 let pixelMap = await image.createPixelMap(imgComponent.byteBuffer, { 133 size:{height: height, width: stride}, srcPixelFormat: 8}); 134 // 裁剪多余的像素 135 pixelMap.cropSync({size:{width:width, height:height}, x:0, y:0}); 136 ``` 137 138 方式三:将原始imgComponent.byteBuffer和stride信息一起传给支持stride的接口处理。 139 140 141 142### 用于显示画面的第二路预览流 143 144获取第二路预览流SurfaceId:创建XComponent组件用于预览流显示,获取surfaceId请参考XComponent组件提供的[getXcomponentSurfaceId](../../reference/apis-arkui/arkui-ts/ts-basic-components-xcomponent.md#getxcomponentsurfaceid9)方法,而XComponent的能力由UI提供,相关介绍可参考[XComponent组件参考](../../reference/apis-arkui/arkui-ts/ts-basic-components-xcomponent.md)。 145 146```ts 147@Component 148struct example { 149 xComponentCtl: XComponentController = new XComponentController(); 150 surfaceId:string = ''; 151 imageWidth: number = 1920; 152 imageHeight: number = 1080; 153 154 build() { 155 XComponent({ 156 id: 'componentId', 157 type: 'surface', 158 controller: this.xComponentCtl 159 }) 160 .onLoad(async () => { 161 console.info('onLoad is called'); 162 this.surfaceId = this.xComponentCtl.getXComponentSurfaceId(); // 获取组件surfaceId 163 // 使用surfaceId创建预览流,开启相机,组件实时渲染每帧预览流数据 164 }) 165 .width(px2vp(this.imageHeight)) 166 .height(px2vp(this.imageWidth)) 167 } 168} 169``` 170 171 172 173### 创建预览流获取数据 174 175通过两个SurfaceId分别创建两路预览流输出,加入相机会话,启动相机会话,获取预览流数据。 176 177```ts 178function createDualPreviewOutput(cameraManager: camera.CameraManager, previewProfile: camera.Profile, 179session: camera.Session, 180imageReceiverSurfaceId: string, xComponentSurfaceId: string): void { 181 // 使用imageReceiverSurfaceId创建第一路预览 182 let previewOutput1 = cameraManager.createPreviewOutput(previewProfile, imageReceiverSurfaceId); 183 if (!previewOutput1) { 184 console.error('createPreviewOutput1 error'); 185 } 186 // 使用xComponentSurfaceId创建第二路预览 187 let previewOutput2 = cameraManager.createPreviewOutput(previewProfile, xComponentSurfaceId); 188 if (!previewOutput2) { 189 console.error('createPreviewOutput2 error'); 190 } 191 // 添加第一路预览流输出 192 session.addOutput(previewOutput1); 193 // 添加第二路预览流输出 194 session.addOutput(previewOutput2); 195} 196``` 197 198## 完整示例 199 200```ts 201import { camera } from '@kit.CameraKit'; 202import { image } from '@kit.ImageKit'; 203import { BusinessError } from '@kit.BasicServicesKit'; 204 205@Entry 206@Component 207struct Index { 208 private imageReceiver: image.ImageReceiver | undefined = undefined; 209 private imageReceiverSurfaceId: string = ''; 210 private xComponentCtl: XComponentController = new XComponentController(); 211 private xComponentSurfaceId: string = ''; 212 @State imageWidth: number = 1920; 213 @State imageHeight: number = 1080; 214 private cameraManager: camera.CameraManager | undefined = undefined; 215 private cameras: Array<camera.CameraDevice> | Array<camera.CameraDevice> = []; 216 private cameraInput: camera.CameraInput | undefined = undefined; 217 private previewOutput1: camera.PreviewOutput | undefined = undefined; 218 private previewOutput2: camera.PreviewOutput | undefined = undefined; 219 private session: camera.VideoSession | undefined = undefined; 220 221 onPageShow(): void { 222 console.info('onPageShow'); 223 this.initImageReceiver(); 224 if (this.xComponentSurfaceId !== '') { 225 this.initCamera(); 226 } 227 } 228 229 onPageHide(): void { 230 console.info('onPageHide'); 231 this.releaseCamera(); 232 } 233 234 /** 235 * 获取ImageReceiver的SurfaceId 236 * @param receiver 237 * @returns 238 */ 239 async initImageReceiver(): Promise<void> { 240 if (!this.imageReceiver) { 241 // 创建ImageReceiver 242 let size: image.Size = { width: this.imageWidth, height: this.imageHeight }; 243 this.imageReceiver = image.createImageReceiver(size, image.ImageFormat.JPEG, 8); 244 // 获取取第一路流SurfaceId 245 this.imageReceiverSurfaceId = await this.imageReceiver.getReceivingSurfaceId(); 246 console.info(`initImageReceiver imageReceiverSurfaceId:${this.imageReceiverSurfaceId}`); 247 // 注册监听处理预览流每帧图像数据 248 this.onImageArrival(this.imageReceiver); 249 } 250 } 251 252 /** 253 * 注册ImageReceiver图像监听 254 * @param receiver 255 */ 256 onImageArrival(receiver: image.ImageReceiver): void { 257 // 注册imageArrival监听 258 receiver.on('imageArrival', () => { 259 console.info('image arrival'); 260 // 获取图像 261 receiver.readNextImage((err: BusinessError, nextImage: image.Image) => { 262 if (err || nextImage === undefined) { 263 console.error('readNextImage failed'); 264 return; 265 } 266 // 解析图像内容 267 nextImage.getComponent(image.ComponentType.JPEG, async (err: BusinessError, imgComponent: image.Component) => { 268 if (err || imgComponent === undefined) { 269 console.error('getComponent failed'); 270 } 271 if (imgComponent.byteBuffer) { 272 // 请参考步骤7解析buffer数据,本示例以方式一为例 273 let width = nextImage.size.width; // 获取图片的宽 274 let height = nextImage.size.height; // 获取图片的高 275 let stride = imgComponent.rowStride; // 获取图片的stride 276 console.debug(`getComponent with width:${width} height:${height} stride:${stride}`); 277 // stride与width一致 278 if (stride == width) { 279 let pixelMap = await image.createPixelMap(imgComponent.byteBuffer, { 280 size: { height: height, width: width }, 281 srcPixelFormat: 8, 282 }) 283 } else { 284 // stride与width不一致 285 const dstBufferSize = width * height * 1.5 // 以NV21为例(YUV_420_SP格式的图片)YUV_420_SP内存计算公式:长x宽+(长x宽)/2 286 const dstArr = new Uint8Array(dstBufferSize) 287 for (let j = 0; j < height * 1.5; j++) { 288 const srcBuf = new Uint8Array(imgComponent.byteBuffer, j * stride, width) 289 dstArr.set(srcBuf, j * width) 290 } 291 let pixelMap = await image.createPixelMap(dstArr.buffer, { 292 size: { height: height, width: width }, 293 srcPixelFormat: 8, 294 }) 295 } 296 } else { 297 console.error('byteBuffer is null'); 298 } 299 // 确保当前buffer没有在使用的情况下,可进行资源释放 300 // 如果对buffer进行异步操作,需要在异步操作结束后再释放该资源(nextImage.release()) 301 nextImage.release(); 302 console.info('image process done'); 303 }) 304 }) 305 }) 306 } 307 308 build() { 309 Column() { 310 XComponent({ 311 id: 'componentId', 312 type: 'surface', 313 controller: this.xComponentCtl 314 }) 315 .onLoad(async () => { 316 console.info('onLoad is called'); 317 this.xComponentSurfaceId = this.xComponentCtl.getXComponentSurfaceId(); // 获取组件surfaceId 318 // 初始化相机,组件实时渲染每帧预览流数据 319 this.initCamera() 320 }) 321 .width(px2vp(this.imageHeight)) 322 .height(px2vp(this.imageWidth)) 323 }.justifyContent(FlexAlign.Center) 324 .height('100%') 325 .width('100%') 326 } 327 328 // 初始化相机 329 async initCamera(): Promise<void> { 330 console.info(`initCamera imageReceiverSurfaceId:${this.imageReceiverSurfaceId} xComponentSurfaceId:${this.xComponentSurfaceId}`); 331 try { 332 // 获取相机管理器实例 333 this.cameraManager = camera.getCameraManager(getContext(this)); 334 if (!this.cameraManager) { 335 console.error('initCamera getCameraManager'); 336 } 337 // 获取当前设备支持的相机device列表 338 this.cameras = this.cameraManager.getSupportedCameras(); 339 if (!this.cameras) { 340 console.error('initCamera getSupportedCameras'); 341 } 342 // 选择一个相机device,创建cameraInput输出对象 343 this.cameraInput = this.cameraManager.createCameraInput(this.cameras[0]); 344 if (!this.cameraInput) { 345 console.error('initCamera createCameraInput'); 346 } 347 // 打开相机 348 await this.cameraInput.open().catch((err: BusinessError) => { 349 console.error(`initCamera open fail: ${JSON.stringify(err)}`); 350 }) 351 // 获取相机device支持的profile 352 let capability: camera.CameraOutputCapability = 353 this.cameraManager.getSupportedOutputCapability(this.cameras[0], camera.SceneMode.NORMAL_VIDEO); 354 if (!capability) { 355 console.error('initCamera getSupportedOutputCapability'); 356 } 357 // 根据业务需求选择一个支持的预览流profile 358 let previewProfile: camera.Profile = capability.previewProfiles[0]; 359 this.imageWidth = previewProfile.size.width; // 更新xComponent组件的宽 360 this.imageHeight = previewProfile.size.height; // 更新xComponent组件的高 361 console.info(`initCamera imageWidth:${this.imageWidth} imageHeight:${this.imageHeight}`); 362 // 使用imageReceiverSurfaceId创建第一路预览 363 this.previewOutput1 = this.cameraManager.createPreviewOutput(previewProfile, this.imageReceiverSurfaceId); 364 if (!this.previewOutput1) { 365 console.error('initCamera createPreviewOutput1'); 366 } 367 // 使用xComponentSurfaceId创建第二路预览 368 this.previewOutput2 = this.cameraManager.createPreviewOutput(previewProfile, this.xComponentSurfaceId); 369 if (!this.previewOutput2) { 370 console.error('initCamera createPreviewOutput2'); 371 } 372 // 创建录像模式相机会话 373 this.session = this.cameraManager.createSession(camera.SceneMode.NORMAL_VIDEO) as camera.VideoSession; 374 if (!this.session) { 375 console.error('initCamera createSession'); 376 } 377 // 开始配置会话 378 this.session.beginConfig(); 379 // 添加相机设备输入 380 this.session.addInput(this.cameraInput); 381 // 添加第一路预览流输出 382 this.session.addOutput(this.previewOutput1); 383 // 添加第二路预览流输出 384 this.session.addOutput(this.previewOutput2); 385 // 提交会话配置 386 await this.session.commitConfig(); 387 // 开始启动已配置的输入输出流 388 await this.session.start(); 389 } catch (error) { 390 console.error(`initCamera fail: ${JSON.stringify(error)}`); 391 } 392 } 393 394 // 释放相机 395 async releaseCamera(): Promise<void> { 396 console.info('releaseCamera E'); 397 try { 398 // 停止当前会话 399 await this.session?.stop(); 400 // 释放相机输入流 401 await this.cameraInput?.close(); 402 // 释放预览输出流 403 await this.previewOutput1?.release(); 404 // 释放拍照输出流 405 await this.previewOutput2?.release(); 406 // 释放会话 407 await this.session?.release(); 408 } catch (error) { 409 console.error(`initCamera fail: ${JSON.stringify(error)}`); 410 } 411 } 412} 413```