1# 深度信息(仅对系统应用开放)(ArkTS) 2 3深度信息表示图像中每个像素点与相机之间的距离关系,可以辅助实现更精准的对焦和背景虚化效果等。在相机应用预览、拍照和录像场景中,支持上报深度信息。 4 5## 开发步骤 6 7详细的API说明请参考[Camera API参考](../../reference/apis-camera-kit/js-apis-camera.md)。 8 91. 导入camera接口,接口中提供了相机相关的属性和方法,导入方法如下。 10 11 ```ts 12 import { camera } from '@kit.CameraKit'; 13 import { BusinessError } from '@kit.BasicServicesKit'; 14 ``` 15 162. 通过[CameraOutputCapability](../../reference/apis-camera-kit/js-apis-camera.md#cameraoutputcapability)类中的depthProfiles属性获取当前设备支持的深度能力,返回depthProfilesArray数组。通过[createDepthDataOutput](../../reference/apis-camera-kit/js-apis-camera-sys.md#createdepthdataoutput)方法创建深度流。 17 18 ```ts 19 function getDepthDataOutput(cameraManager: camera.CameraManager, cameraOutputCapability: camera.CameraOutputCapability): camera.DepthDataOutput | undefined { 20 let depthProfilesArray: Array<camera.DepthProfile> = cameraOutputCapability.depthProfiles; 21 if (!depthProfilesArray) { 22 console.error("createOutput depthProfilesArray is null"); 23 } 24 let depthDataOutput: camera.DepthDataOutput | undefined = undefined; 25 try { 26 depthDataOutput = cameraManager.createDepthDataOutput(depthProfilesArray[0]); 27 } catch (error) { 28 let err = error as BusinessError; 29 console.error(`Failed to create the DepthDataOutput instance. error: ${err}`); 30 } 31 return depthDataOutput; 32 } 33 ``` 34 353. 使能。通过depthDataOutput类的[start](../../reference/apis-camera-kit/js-apis-camera-sys.md#start13)方法输出深度流。接口调用失败会返回相应错误码,错误码类型参见[Camera错误码](../../reference/apis-camera-kit/js-apis-camera.md#cameraerrorcode)。 36 37 ```ts 38 async function startDepthDataOutput(depthDataOutput: camera.DepthDataOutput): Promise<void> { 39 if (!depthDataOutput) { 40 console.error('depthDataOutput Undefined'); 41 return; 42 } 43 try { 44 await depthDataOutput.start(); 45 } catch (err) { 46 const error = err as BusinessError; 47 console.error(`Failed to start depth data output. error: ${err}`); 48 } 49 } 50 ``` 51 52## 状态监听 53 54在相机应用开发过程中,可以随时监听深度流的深度数据回调信息,以及深度流输出错误信息。 55 56- 通过注册固定的depthDataAvailable回调函数获取监听深度流数据。 57 58 ```ts 59 function onDepthDataAvailable(depthDataOutput: camera.DepthDataOutput): void { 60 depthDataOutput.on('depthDataAvailable', (err: BusinessError) => { 61 if (err !== undefined && err.code !== 0) { 62 return; 63 } 64 console.info('Depth data available'); 65 }); 66 } 67 ``` 68 69- 通过注册固定的error回调函数获取监听深度流输出错误结果,callback返回深度输出接口使用错误时对应的错误码,错误码类型参见[Camera错误码](../../reference/apis-camera-kit/js-apis-camera.md#cameraerrorcode)。 70 71 ```ts 72 function onDepthDataOutputError(depthDataOutput: camera.DepthDataOutput): void { 73 depthDataOutput.on('error', (depthDataOutputError: BusinessError) => { 74 console.error(`Depth data output error code: ${depthDataOutputError.code}`); 75 }); 76 } 77 ``` 78