camera.md 19.8 KB
Newer Older
T
tongxu-liu1 已提交
1 2 3 4
# 相机开发指导

## 场景介绍

S
supeng 已提交
5 6 7 8 9 10 11
OpenHarmony相机模块支持相机业务的开发,开发者可以通过已开放的接口实现相机硬件的访问、操作和新功能开发,最常见的操作如:预览、拍照和录像等。开发者也可以通过合适的接口或者接口组合实现闪光灯控制、曝光时间控制、手动对焦和自动对焦控制、变焦控制以及更多的功能。

开发者在调用Camera能力时,需要了解Camera的一些基本概念:

- **相机静态能力**:用于描述相机的固有能力的一系列参数,比如朝向、支持的分辨率等信息。
- **物理相机**:物理相机就是独立的实体摄像头设备。物理相机ID是用于标志每个物理摄像头的唯一字串。
- **异步操作**:为保证UI线程不被阻塞,大部分Camera调用都是异步的。对于每个API均提供了callback函数和Promise函数。
T
tongxu-liu1 已提交
12 13 14 15 16 17 18 19 20

## 开发步骤

### 接口说明

详细API含义请参考:[相机管理API文档](../reference/apis/js-apis-camera.md)

### 全流程场景

S
supeng 已提交
21
包含流程:权限申请、创建实例、参数设置、会话管理、拍照、录像、释放资源等。
T
tongxu-liu1 已提交
22

T
tongxu-liu1 已提交
23
Xcomponent创建方法可参考:[XComponent创建方法](#xcomponent创建方法)
T
tongxu-liu1 已提交
24

25
拍照保存接口可参考:[图片处理API文档](image.md#imagereceiver的使用)
T
tongxu-liu1 已提交
26

S
supeng 已提交
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
#### 权限申请

在使用相机之前,需要申请相机的相关权限,保证应用拥有相机硬件及其他功能权限,应用权限的介绍请参考权限章节,相机涉及权限如下表。

| 权限名称 | 权限属性值                     |
| -------- | ------------------------------ |
| 相机权限 | ohos.permission.CAMERA         |
| 录音权限 | ohos.permission.MICROPHONE     |
| 存储权限 | ohos.permission.WRITE_MEDIA    |
| 读取权限 | ohos.permission.READ_MEDIA     |
| 位置权限 | ohos.permission.MEDIA_LOCATION |

参考代码如下:

```typescript
const PERMISSIONS: Array<string> = [
    'ohos.permission.CAMERA',
    'ohos.permission.MICROPHONE',
    'ohos.permission.MEDIA_LOCATION',
    'ohos.permission.READ_MEDIA',
    'ohos.permission.WRITE_MEDIA'
]

function applyPermission() {
        console.info('[permission] get permission');
        globalThis.abilityContext.requestPermissionFromUser(PERMISSIONS)
    }
```

T
tongxu-liu1 已提交
56 57
#### 创建实例

S
supeng 已提交
58 59
在实现一个相机应用之前必须先创建一个独立的相机设备,然后才能继续相机的其他操作。如果此步骤操作失败,相机可能被占用或无法使用。如果被占用,必须等到相机释放后才能重新获取CameraManager对象。通过getSupportedCameras() 方法,获取当前使用的设备支持的相机列表。相机列表中存储了当前设备拥有的所有相机ID,如果列表不为空,则列表中的每个ID都支持独立创建相机对象;否则,说明正在使用的设备无可用的相机,不能继续后续的操作。相机设备具备预览、拍照、录像、Metadata等输出流,需要通过getSupportedOutputCapability()接口获取各个输出流的具体能力,通过该接口,可以获取当前设备支持的所有输出流能力,分别在CameraOutputCapability中的各个profile字段中,相机设备创建的建议步骤如下:

T
tongxu-liu1 已提交
60
```js
T
tongxu-liu1 已提交
61 62 63
import camera from '@ohos.multimedia.camera'
import image from '@ohos.multimedia.image'
import media from '@ohos.multimedia.media'
T
tongxu-liu1 已提交
64 65
import featureAbility from '@ohos.ability.featureAbility'

66
// 创建CameraManager对象
T
tongxu-liu1 已提交
67
let cameraManager
S
supeng 已提交
68
await camera.getCameraManager(null, (err, manager) => {
T
tongxu-liu1 已提交
69 70 71 72 73 74 75 76
    if (err) {
        console.error('Failed to get the CameraManager instance ${err.message}');
        return;
    }
    console.log('Callback returned with the CameraManager instance');
    cameraManager = manager
})

77
// 注册回调函数监听相机状态变化,获取状态变化的相机信息
T
tongxu-liu1 已提交
78 79 80 81 82
cameraManager.on('cameraStatus', (cameraStatusInfo) => {
    console.log('camera : ' + cameraStatusInfo.camera.cameraId);
    console.log('status: ' + cameraStatusInfo.status);
})

83
// 获取相机列表
T
tongxu-liu1 已提交
84
let cameraArray
S
supeng 已提交
85
await cameraManager.getSupportedCameras(async (err, cameras) => {
T
tongxu-liu1 已提交
86 87 88 89 90 91 92 93
    if (err) {
        console.error('Failed to get the cameras. ${err.message}');
        return;
    }
    console.log('Callback returned with an array of supported cameras: ' + cameras.length);
    cameraArray = cameras
})

S
supeng 已提交
94 95 96 97 98
for (let index = 0; index < cameraArray.length; index++) {
    console.log('cameraId : ' + cameraArray[index].cameraId)                          // 获取相机ID
    console.log('cameraPosition : ' + cameraArray[index].cameraPosition)              // 获取相机位置
    console.log('cameraType : ' + cameraArray[index].cameraType)                      // 获取相机类型
    console.log('connectionType : ' + cameraArray[index].connectionType)              // 获取相机连接类型
Mr-YX's avatar
Mr-YX 已提交
99 100
}

101
// 创建相机输入流
Mr-YX's avatar
Mr-YX 已提交
102 103
let cameraInput
await cameraManager.createCameraInput(cameraArray[0].cameraId).then((input) => {
T
tongxu-liu1 已提交
104 105 106 107
    console.log('Promise returned with the CameraInput instance');
    cameraInput = input
})

S
supeng 已提交
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
// 获取相机设备支持的输出流能力
let cameraOutputCap = await camera.getSupportedOutputCapability(cameraInput);
if (!cameraOutputCap) {
    console.info("outputCapability outputCapability == null || undefined")
} else {
    console.info("outputCapability: " + JSON.stringify(cameraOutputCap));
}

let previewProfilesArray = cameraOutputCap.previewProfiles;
if (!previewProfilesArray) {
    console.info("createOutput previewProfilesArray == null || undefined")
} 

let photoProfilesArray = cameraOutputCap.photoProfiles;
if (!photoProfilesArray) {
    console.info("createOutput photoProfilesArray == null || undefined")
} 

let videoProfilesArray = cameraOutputCap.videoProfiles;
if (!videoProfilesArray) {
    console.info("createOutput videoProfilesArray == null || undefined")
} 

let metadataObjectTypesArray = cameraOutputCap.supportedMetadataObjectTypes;
if (!metadataObjectTypesArray) {
    console.info("createOutput metadataObjectTypesArray == null || undefined")
}

136
// 创建预览输出流
T
tongxu-liu1 已提交
137
let previewOutput
S
supeng 已提交
138
camera.createPreviewOutput(previewProfilesArray[0], surfaceId, async (err, output) => {
T
tongxu-liu1 已提交
139 140 141 142 143 144 145 146
    if (err) {
        console.error('Failed to create the PreviewOutput instance. ${err.message}');
        return;
    }
    console.log('Callback returned with previewOutput instance');
    previewOutput = output
});

147
// 创建ImageReceiver对象,并设置照片参数
T
tongxu-liu1 已提交
148
let imageReceiver = await image.createImageReceiver(1920, 1080, 4, 8)
149
// 获取照片显示SurfaceId
T
tongxu-liu1 已提交
150
let photoSurfaceId = await imageReceiver.getReceivingSurfaceId()
151
// 创建拍照输出流
T
tongxu-liu1 已提交
152
let photoOutput
S
supeng 已提交
153
await camera.createPhotoOutput(photoProfilesArray[0], photoSurfaceId, async (err, output) => {
T
tongxu-liu1 已提交
154 155 156 157 158 159 160 161
    if (err) {
        console.error('Failed to create the PhotoOutput instance. ${err.message}');
        return;
    }
    console.log('Callback returned with the PhotoOutput instance.');
    photoOutput = output
});

162
// 创建视频录制的参数
T
tongxu-liu1 已提交
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
let videoProfile = {
    audioBitrate : 48000,
    audioChannels : 2,
    audioCodec : 'audio/mp4a-latm',
    audioSampleRate : 48000,
    fileFormat : 'mp4',
    videoBitrate : 48000,
    videoCodec : 'video/mp4v-es',
    videoFrameWidth : 640,
    videoFrameHeight : 480,
    videoFrameRate : 30
}
let videoConfig = {
    audioSourceType : 1,
    videoSourceType : 0,
    profile : videoProfile,
    url : 'file:///data/media/01.mp4',
    orientationHint : 0,
    location : { latitude : 30, longitude : 130 },
}

184
// 创建录像输出流
T
tongxu-liu1 已提交
185 186 187 188 189
let videoRecorder
await media.createVideoRecorder().then((recorder) => {
    console.log('createVideoRecorder called')
    videoRecorder = recorder
})
190
// 设置视频录制的参数
T
tongxu-liu1 已提交
191 192 193 194 195 196
await videoRecorder.prepare(videoConfig)
//获取录像SurfaceId
await videoRecorder.getInputSurface().then((id) => {
    console.log('getInputSurface called')
    videoSurfaceId = id
})
S
supeng 已提交
197

198
// 创建VideoOutput对象
T
tongxu-liu1 已提交
199
let videoOutput
S
supeng 已提交
200 201 202 203 204 205
camera.createVideoOutput(videoProfile, videoSurfaceId, async (err, data) => {
    if (!err) {
        console.info("Callback returned with create video output successfully.");
        videoOutput = data;
    } else {
        console.info("Failed to create video output, err: " + err.message);
T
tongxu-liu1 已提交
206 207
    }
});
S
supeng 已提交
208 209
```
预览流、拍照流和录像流的输入均需要提前创建surface,其中预览流为XComponent组件提供的surface,拍照流为ImageReceiver提供的surface,录像流为VideoRecorder的surface。
T
tongxu-liu1 已提交
210

S
supeng 已提交
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
**XComponent**

```typescript
mXComponentController: XComponentController = new XComponentController                   // 创建XComponentController

build() {
    Flex() {
        XComponent({                                                                     // 创建XComponent
            id: '',
            type: 'surface',
            libraryname: '',
            controller: this.mXComponentController
        })
        .onload(() => {                                                                  // 设置onload回调
            // 设置Surface宽高(1920*1080)
            this.mXComponentController.setXComponentSurfaceSize({surfaceWidth:1920,surfaceHeight:1080})
            // 获取Surface ID
            globalThis.surfaceId = mXComponentController.getXComponentSurfaceId()
        })
        .width('1920px')                                                                 // 设置XComponent宽度
        .height('1080px')                                                                // 设置XComponent高度
    }
}
```

**ImageReceiver**

```typescript
function getImageReceiverSurfaceId() {
    var receiver = image.createImageReceiver(640, 480, 4, 8)
    console.log(TAG + 'before ImageReceiver check')
    if (receiver !== undefined) {
      console.log('ImageReceiver is ok')
      surfaceId1 = await receiver.getReceivingSurfaceId()
      console.log('ImageReceived id: ' + JSON.stringify(surfaceId1))
    } else {
      console.log('ImageReceiver is not ok')
    }
  }
```

**VideoRecorder**

```typescript
function getVideoRecorderSurface() {
        await getFd('CameraManager.mp4');
        mVideoConfig.url = mFdPath;
        media.createVideoRecorder((err, recorder) => {
            console.info('Entering create video receiver')
            mVideoRecorder = recorder
            console.info('videoRecorder is :' + JSON.stringify(mVideoRecorder))
            console.info('videoRecorder.prepare called.')
            mVideoRecorder.prepare(mVideoConfig, (err) => {
                console.info('videoRecorder.prepare success.')
                mVideoRecorder.getInputSurface((err, id) => {
                    console.info('getInputSurface called')
                    mVideoSurface = id
                    console.info('getInputSurface surfaceId: ' + JSON.stringify(mVideoSurface))
                })
            })
        })
    }
T
tongxu-liu1 已提交
273 274 275 276 277
```

#### 参数设置

```js
278
// 判断设备是否支持闪光灯
T
tongxu-liu1 已提交
279
let flashStatus
S
supeng 已提交
280
await cameraInput.hasFlash().then(async (status) => {
T
tongxu-liu1 已提交
281 282 283 284
    console.log('Promise returned with the flash light support status:' + status);
    flashStatus = status
})
if(flashStatus) {
285
    // 判断是否支持自动闪光灯模式
T
tongxu-liu1 已提交
286
    let flashModeStatus
S
supeng 已提交
287
    cameraInput.isFlashModeSupported(camera.FlashMode.FLASH_MODE_AUTO, async (err, status) => {
T
tongxu-liu1 已提交
288 289 290 291 292 293 294 295
        if (err) {
            console.error('Failed to check whether the flash mode is supported. ${err.message}');
            return;
        }
        console.log('Callback returned with the flash mode support status: ' + status);
        flashModeStatus = status
    })
    if(flashModeStatus) {
296
        // 设置自动闪光灯模式
S
supeng 已提交
297
        cameraInput.setFlashMode(camera.FlashMode.FLASH_MODE_AUTO, async (err) => {
T
tongxu-liu1 已提交
298 299 300 301 302 303 304 305 306
            if (err) {
                console.error('Failed to set the flash mode  ${err.message}');
                return;
            }
            console.log('Callback returned with the successful execution of setFlashMode.');
        })
    }
}

307
// 判断是否支持连续自动变焦模式
T
tongxu-liu1 已提交
308
let focusModeStatus
S
supeng 已提交
309
cameraInput.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO, async (err, status) => {
T
tongxu-liu1 已提交
310 311 312 313 314 315 316 317
    if (err) {
        console.error('Failed to check whether the focus mode is supported. ${err.message}');
        return;
    }
    console.log('Callback returned with the focus mode support status: ' + status);
    focusModeStatus = status
})
if(focusModeStatus) {
318
    // 设置连续自动变焦模式
S
supeng 已提交
319
    cameraInput.setFocusMode(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO, async (err) => {
T
tongxu-liu1 已提交
320 321 322 323 324 325 326 327
        if (err) {
            console.error('Failed to set the focus mode  ${err.message}');
            return;
        }
        console.log('Callback returned with the successful execution of setFocusMode.');
    })
}

328
// 获取相机支持的可变焦距比范围
T
tongxu-liu1 已提交
329
let zoomRatioRange
S
supeng 已提交
330
cameraInput.getZoomRatioRange(async (err, range) => {
T
tongxu-liu1 已提交
331 332 333 334 335 336 337 338
    if (err) {
        console.error('Failed to get the zoom ratio range. ${err.message}');
        return;
    }
    console.log('Callback returned with zoom ratio range: ' + range.length);
    zoomRatioRange = range
})

339
// 设置可变焦距比
S
supeng 已提交
340
cameraInput.setZoomRatio(zoomRatioRange[0], async (err) => {
T
tongxu-liu1 已提交
341 342 343 344 345 346 347 348 349 350 351 352 353
    if (err) {
        console.error('Failed to set the zoom ratio value ${err.message}');
        return;
    }
    console.log('Callback returned with the successful execution of setZoomRatio.');
})
```

#### 会话管理

##### 创建会话

```js
354
// 创建Context对象
T
tongxu-liu1 已提交
355 356 357 358
let context = featureAbility.getContext()

//创建会话
let captureSession
S
supeng 已提交
359
await camera.createCaptureSession((err, session) => {
T
tongxu-liu1 已提交
360 361 362 363 364 365 366 367
    if (err) {
        console.error('Failed to create the CaptureSession instance. ${err.message}');
        return;
    }
    console.log('Callback returned with the CaptureSession instance.' + session);
    captureSession = session
});

368
// 开始配置会话
S
supeng 已提交
369
await captureSession.beginConfig(async (err) => {
T
tongxu-liu1 已提交
370 371 372 373 374 375 376
    if (err) {
        console.error('Failed to start the configuration. ${err.message}');
        return;
    }
    console.log('Callback invoked to indicate the begin config success.');
});

377
// 向会话中添加相机输入流
S
supeng 已提交
378
await captureSession.addInput(cameraInput, async (err, data) => {
T
tongxu-liu1 已提交
379 380 381 382 383 384 385
    if (err) {
        console.error('Failed to add the CameraInput instance. ${err.message}');
        return;
    }
    console.log('Callback invoked to indicate that the CameraInput instance is added.');
});

386
// 向会话中添加预览输入流
S
supeng 已提交
387
await captureSession.addOutput(previewOutput, async (err, data) => {
T
tongxu-liu1 已提交
388 389 390 391 392 393 394
    if (err) {
        console.error('Failed to add the PreviewOutput instance ${err.message}');
        return;
    }
    console.log('Callback invoked to indicate that the PreviewOutput instance is added.');
});

395
// 向会话中添加拍照输出流
S
supeng 已提交
396
await captureSession.addOutput(photoOutput, async (err, data) => {
T
tongxu-liu1 已提交
397 398 399 400 401 402 403
    if (err) {
        console.error('Failed to add the PhotoOutput instance ${err.message}');
        return;
    }
    console.log('Callback invoked to indicate that the PhotoOutput instance is added.');
});

404
// 提交会话配置
S
supeng 已提交
405
await captureSession.commitConfig(async (err) => {
T
tongxu-liu1 已提交
406 407 408 409 410 411 412
    if (err) {
        console.error('Failed to commit the configuration. ${err.message}');
        return;
    }
    console.log('Callback invoked to indicate the commit config success.');
});

413
// 启动会话
T
tongxu-liu1 已提交
414 415 416 417 418 419 420 421
await captureSession.start().then(() => {
    console.log('Promise returned to indicate the session start success.');
})
```

##### 切换会话

```js
422
// 停止当前会话
S
supeng 已提交
423
await captureSession.stop(async (err) => {
T
tongxu-liu1 已提交
424 425 426 427 428 429 430
    if (err) {
        console.error('Failed to stop the session ${err.message}');
        return;
    }
    console.log('Callback invoked to indicate the session stop success.');
});

431
// 开始配置会话
S
supeng 已提交
432
await captureSession.beginConfig(async (err) => {
T
tongxu-liu1 已提交
433 434 435 436 437 438 439
    if (err) {
        console.error('Failed to start the configuration. ${err.message}');
        return;
    }
    console.log('Callback invoked to indicate the begin config success.');
});

440
// 从会话中移除拍照输出流
S
supeng 已提交
441
await captureSession.removeOutput(photoOutput, async (err) => {
T
tongxu-liu1 已提交
442 443 444 445 446 447 448
    if (err) {
        console.error('Failed to remove the PhotoOutput instance. ${err.message}');
        return;
    }
    console.log('Callback invoked to indicate that the PhotoOutput instance is removed.');
});

449
// 向会话中添加录像输出流
S
supeng 已提交
450
await captureSession.addOutput(videoOutput, async (err) => {
T
tongxu-liu1 已提交
451 452 453 454 455 456 457
    if (err) {
        console.error('Failed to add the VideoOutput instance ${err.message}');
        return;
    }
    console.log('Callback invoked to indicate that the VideoOutput instance is added.');
});

458
// 提交会话配置
S
supeng 已提交
459
await captureSession.commitConfig(async (err) => {
T
tongxu-liu1 已提交
460 461 462 463 464 465 466
    if (err) {
        console.error('Failed to commit the configuration. ${err.message}');
        return;
    }
    console.log('Callback invoked to indicate the commit config success.');
});

467
// 启动会话
T
tongxu-liu1 已提交
468 469 470 471 472 473 474 475 476
await captureSession.start().then(() => {
    console.log('Promise returned to indicate the session start success.');
})
```

#### 拍照

```js
let settings = {
477 478
    quality: camera.QualityLevel.QUALITY_LEVEL_HIGH,                                     // 设置图片质量高
    rotation: camera.ImageRotation.ROTATION_0                                            // 设置图片旋转角度0
T
tongxu-liu1 已提交
479
}
480
// 使用当前拍照设置进行拍照
S
supeng 已提交
481
photoOutput.capture(settings, async (err) => {
T
tongxu-liu1 已提交
482 483 484 485 486 487 488 489 490 491 492
    if (err) {
        console.error('Failed to capture the photo ${err.message}');
        return;
    }
    console.log('Callback invoked to indicate the photo capture request success.');
});
```

#### 录像

```js
493
// 启动录像输出流
S
supeng 已提交
494
videoOutput.start(async (err) => {
T
tongxu-liu1 已提交
495 496 497 498 499 500 501
    if (err) {
        console.error('Failed to start the video output ${err.message}');
        return;
    }
    console.log('Callback invoked to indicate the video output start success.');
});

502
// 开始录像
T
tongxu-liu1 已提交
503 504 505 506
await videoRecorder.start().then(() => {
    console.info('videoRecorder start success');
}

507
// 停止录像
T
tongxu-liu1 已提交
508 509 510 511
await videoRecorder.stop().then(() => {
    console.info('stop success');
}

512
// 停止录像输出流
T
tongxu-liu1 已提交
513 514 515 516 517 518 519 520 521 522 523 524
await videoOutput.stop((err) => {
    if (err) {
        console.error('Failed to stop the video output ${err.message}');
        return;
    }
    console.log('Callback invoked to indicate the video output stop success.');
});
```

#### 释放资源

```js
525
// 停止当前会话
S
supeng 已提交
526
await captureSession.stop(async (err) => {
T
tongxu-liu1 已提交
527 528 529 530 531 532
    if (err) {
        console.error('Failed to stop the session ${err.message}');
        return;
    }
    console.log('Callback invoked to indicate the session stop success.');
});
533
// 释放相机输入流
S
supeng 已提交
534
await cameraInput.release(async (err) => {
T
tongxu-liu1 已提交
535 536 537 538 539 540
    if (err) {
        console.error('Failed to release the CameraInput instance ${err.message}');
        return;
    }
    console.log('Callback invoked to indicate that the CameraInput instance is released successfully.');
});
541
// 释放预览输出流
S
supeng 已提交
542
await previewOutput.release(async (err) => {
T
tongxu-liu1 已提交
543 544 545 546 547 548
    if (err) {
        console.error('Failed to release the PreviewOutput instance ${err.message}');
        return;
    }
    console.log('Callback invoked to indicate that the PreviewOutput instance is released successfully.');
});
549
// 释放拍照输出流
S
supeng 已提交
550
await photoOutput.release(async (err) => {
T
tongxu-liu1 已提交
551 552 553 554 555 556
    if (err) {
        console.error('Failed to release the PhotoOutput instance ${err.message}');
        return;
    }
    console.log('Callback invoked to indicate that the PhotoOutput instance is released successfully.');
});
557
// 释放录像输出流
S
supeng 已提交
558
await videoOutput.release(async (err) => {
T
tongxu-liu1 已提交
559 560 561 562 563 564
    if (err) {
        console.error('Failed to release the VideoOutput instance ${err.message}');
        return;
    }
    console.log('Callback invoked to indicate that the VideoOutput instance is released successfully.');
});
565
// 释放会话
S
supeng 已提交
566
await captureSession.release(async (err) => {
T
tongxu-liu1 已提交
567 568 569 570 571 572
    if (err) {
        console.error('Failed to release the CaptureSession instance ${err.message}');
        return;
    }
    console.log('Callback invoked to indicate that the CaptureSession instance is released successfully.');
});
T
tongxu-liu1 已提交
573 574
```

S
supeng 已提交
575
## 流程图
T
tongxu-liu1 已提交
576

S
supeng 已提交
577 578
应用使用相机的流程示意图如下
![camera_framework process](figures/camera_framework_process.jpg)