1# 拍照(C/C++) 2 3拍照是相机的最重要功能之一,拍照模块基于相机复杂的逻辑,为了保证用户拍出的照片质量,在中间步骤可以设置分辨率、闪光灯、焦距、照片质量及旋转角度等信息。 4 5## 开发步骤 6 7详细的API说明请参考[Camera API参考](../../reference/apis-camera-kit/_o_h___camera.md)。 8 91. 导入NDK接口,接口中提供了相机相关的属性和方法,导入方法如下。 10 11 ```c++ 12 // 导入NDK接口头文件。 13 #include <cstdint> 14 #include <cstdlib> 15 #include <cstring> 16 #include <string.h> 17 #include "hilog/log.h" 18 #include "ohcamera/camera.h" 19 #include "ohcamera/camera_input.h" 20 #include "ohcamera/capture_session.h" 21 #include "ohcamera/photo_output.h" 22 #include "ohcamera/preview_output.h" 23 #include "ohcamera/video_output.h" 24 #include "ohcamera/camera_manager.h" 25 #include <multimedia/image_framework/image/image_native.h> 26 ``` 27 282. 在CMake脚本中链接相关动态库。 29 30 ```txt 31 target_link_libraries(entry PUBLIC 32 libace_napi.z.so 33 libhilog_ndk.z.so 34 libnative_buffer.so 35 libohcamera.so 36 libohimage.so 37 libohfileuri.so 38 ) 39 ``` 40 413. 创建并打开相机设备,参考[ 设备输入(C/C++)](./native-camera-device-input.md)步骤3-5。 42 434. 选择设备支持的输出流能力,创建拍照输出流。 44 45 通过[OH_CameraManager_CreatePhotoOutputWithoutSurface()](../../reference/apis-camera-kit/_o_h___camera.md#oh_cameramanager_createphotooutputwithoutsurface)方法创建拍照输出流。 46 47 ```c++ 48 Camera_PhotoOutput* CreatePhotoOutput(Camera_Manager* cameraManager, const Camera_Profile* photoProfile) { 49 Camera_PhotoOutput* photoOutput = nullptr; 50 // 无需传入surfaceId,直接创建拍照流。 51 Camera_ErrorCode ret = OH_CameraManager_CreatePhotoOutputWithoutSurface(cameraManager, photoProfile, &photoOutput); 52 if (photoOutput == nullptr || ret != CAMERA_OK) { 53 OH_LOG_ERROR(LOG_APP, "OH_CameraManager_CreatePhotoOutputWithoutSurface failed."); 54 } 55 return photoOutput; 56 } 57 ``` 58 595. 注册单段式(PhotoAvailable)拍照回调,若应用希望快速得到回图,推荐使用[分段式拍照回调(PhotoAssetAvailable)](./native-camera-deferred-capture.md)。 60 61 > **注意:** 62 > 63 > 如果已经注册了PhotoAssetAvailable回调,并且在Session开始之后又注册了PhotoAvailable回调,PhotoAssetAvailable和PhotoAvailable同时注册,会导致流被重启,仅PhotoAssetAvailable生效。 64 > 65 > 不建议开发者同时注册PhotoAssetAvailable和PhotoAvailable。 66 67 **单段式拍照开发流程(PhotoAssetAvailable)**: 68 69 - 在会话commitConfig前注册单段式拍照回调。 70 - 在单段式拍照回调函数中获取图片信息,解析出buffer数据,做自定义业务处理。 71 - 将处理完的buffer通过回调传给ArkTS侧,做图片显示或通过安全控件写文件保存图片。 72 - 使用完后解注册单段式拍照回调函数。 73 74 ```c++ 75 // 保存NAPI侧注册的buffer处理回调函数。 76 static void* bufferCb = nullptr; 77 Camera_ErrorCode RegisterBufferCb(void* cb) { 78 OH_LOG_INFO(LOG_APP, " RegisterBufferCb start"); 79 if (cb == nullptr) { 80 OH_LOG_INFO(LOG_APP, " RegisterBufferCb invalid error"); 81 return CAMERA_INVALID_ARGUMENT; 82 } 83 bufferCb = cb; 84 return CAMERA_OK; 85 } 86 87 // 单段式拍照回调函数。 88 void OnPhotoAvailable(Camera_PhotoOutput* photoOutput, OH_PhotoNative* photo) { 89 OH_LOG_INFO(LOG_APP, "OnPhotoAvailable start!"); 90 OH_ImageNative* imageNative; 91 Camera_ErrorCode errCode = OH_PhotoNative_GetMainImage(photo, &imageNative); 92 OH_LOG_INFO(LOG_APP, "OnPhotoAvailable errCode:%{public}d imageNative:%{public}p", errCode, imageNative); 93 // 读取OH_ImageNative的 size 属性。 94 Image_Size size; 95 Image_ErrorCode imageErr = OH_ImageNative_GetImageSize(imageNative, &size); 96 OH_LOG_INFO(LOG_APP, "OnPhotoAvailable imageErr:%{public}d width:%{public}d height:%{public}d", imageErr, 97 size.width, size.height); 98 // 读取OH_ImageNative的组件列表的元素个数。 99 size_t componentTypeSize = 0; 100 imageErr = OH_ImageNative_GetComponentTypes(imageNative, nullptr, &componentTypeSize); 101 OH_LOG_INFO(LOG_APP, "OnPhotoAvailable imageErr:%{public}d componentTypeSize:%{public}zu", imageErr, 102 componentTypeSize); 103 // 读取OH_ImageNative的组件列表。 104 uint32_t* components = new uint32_t[componentTypeSize]; 105 imageErr = OH_ImageNative_GetComponentTypes(imageNative, &components, &componentTypeSize); 106 OH_LOG_INFO(LOG_APP, "OnPhotoAvailable OH_ImageNative_GetComponentTypes imageErr:%{public}d", imageErr); 107 // 读取OH_ImageNative的第一个组件所对应的缓冲区对象。 108 OH_NativeBuffer* nativeBuffer = nullptr; 109 imageErr = OH_ImageNative_GetByteBuffer(imageNative, components[0], &nativeBuffer); 110 OH_LOG_INFO(LOG_APP, "OnPhotoAvailable OH_ImageNative_GetByteBuffer imageErr:%{public}d", imageErr); 111 // 读取OH_ImageNative的第一个组件所对应的缓冲区大小。 112 size_t nativeBufferSize = 0; 113 imageErr = OH_ImageNative_GetBufferSize(imageNative, components[0], &nativeBufferSize); 114 OH_LOG_INFO(LOG_APP, "OnPhotoAvailable imageErr:%{public}d nativeBufferSize:%{public}zu", imageErr, 115 nativeBufferSize); 116 // 读取OH_ImageNative的第一个组件所对应的像素行宽。 117 int32_t rowStride = 0; 118 imageErr = OH_ImageNative_GetRowStride(imageNative, components[0], &rowStride); 119 OH_LOG_INFO(LOG_APP, "OnPhotoAvailable imageErr:%{public}d rowStride:%{public}d", imageErr, rowStride); 120 // 读取OH_ImageNative的第一个组件所对应的像素大小。 121 int32_t pixelStride = 0; 122 imageErr = OH_ImageNative_GetPixelStride(imageNative, components[0], &pixelStride); 123 OH_LOG_INFO(LOG_APP, "OnPhotoAvailable imageErr:%{public}d pixelStride:%{public}d", imageErr, pixelStride); 124 // 将ION内存映射到进程空间。 125 void* virAddr = nullptr; // 指向映射内存的虚拟地址,解除映射后这个指针将不再有效。 126 int32_t ret = OH_NativeBuffer_Map(nativeBuffer, &virAddr); // 映射后通过第二个参数virAddr返回内存的首地址。 127 OH_LOG_INFO(LOG_APP, "OnPhotoAvailable OH_NativeBuffer_Map err:%{public}d", ret); 128 // 调用NAPI层buffer回调。 129 auto cb = (void (*)(void *, size_t))(bufferCb); 130 cb(virAddr, nativeBufferSize); 131 // 释放资源。 132 delete[] components; 133 OH_ImageNative_Release(imageNative); 134 ret = OH_NativeBuffer_Unmap(nativeBuffer); // 在处理完之后,解除映射并释放缓冲区。 135 if (ret != 0) { 136 OH_LOG_ERROR(LOG_APP, "OnPhotoAvailable OH_NativeBuffer_Unmap error:%{public}d", ret); 137 } 138 OH_LOG_INFO(LOG_APP, "OnPhotoAvailable end"); 139 } 140 141 // 注册单段式拍照回调。 142 Camera_ErrorCode PhotoOutputRegisterPhotoAvailableCallback(Camera_PhotoOutput* photoOutput) { 143 OH_LOG_INFO(LOG_APP, "PhotoOutputRegisterPhotoAvailableCallback start!"); 144 Camera_ErrorCode ret = OH_PhotoOutput_RegisterPhotoAvailableCallback(photoOutput, OnPhotoAvailable); 145 if (ret != CAMERA_OK) { 146 OH_LOG_ERROR(LOG_APP, "PhotoOutputRegisterPhotoAvailableCallback failed."); 147 } 148 OH_LOG_INFO(LOG_APP, "PhotoOutputRegisterPhotoAvailableCallback return with ret code: %{public}d!", ret); 149 return ret; 150 } 151 152 // 解注册单段式拍照回调。 153 Camera_ErrorCode PhotoOutputUnRegisterPhotoAvailableCallback(Camera_PhotoOutput* photoOutput) { 154 OH_LOG_INFO(LOG_APP, "PhotoOutputUnRegisterPhotoAvailableCallback start!"); 155 Camera_ErrorCode ret = OH_PhotoOutput_UnregisterPhotoAvailableCallback(photoOutput, OnPhotoAvailable); 156 if (ret != CAMERA_OK) { 157 OH_LOG_ERROR(LOG_APP, "PhotoOutputUnRegisterPhotoAvailableCallback failed."); 158 } 159 OH_LOG_INFO(LOG_APP, "PhotoOutputUnRegisterPhotoAvailableCallback return with ret code: %{public}d!", ret); 160 return ret; 161 } 162 ``` 163 164 NAPI层buffer回处理参考示例代码: 165 166 ```c++ 167 static napi_ref bufferCbRef_ = nullptr; 168 static napi_env env_; 169 size_t g_size = 0; 170 171 // NAPI层buffer回调方法。 172 static void BufferCb(void* buffer, size_t size) { 173 OH_LOG_INFO(LOG_APP, "BufferCb size:%{public}zu", size); 174 g_size = size; 175 napi_value asyncResource = nullptr; 176 napi_value asyncResourceName = nullptr; 177 napi_async_work work; 178 179 void* copyBuffer = malloc(size); 180 if (copyBuffer == nullptr) { 181 return; 182 } 183 OH_LOG_INFO(LOG_APP, "BufferCb copyBuffer:%{public}p", copyBuffer); 184 // 使用 std::memcpy 复制 buffer 的内容到 copyBuffer。 185 std::memcpy(copyBuffer, buffer, size); 186 napi_create_string_utf8(env_, "BufferCb", NAPI_AUTO_LENGTH, &asyncResourceName); 187 napi_status status = napi_create_async_work( 188 env_, asyncResource, asyncResourceName, [](napi_env env, void* copyBuffer) {}, 189 [](napi_env env, napi_status status, void* copyBuffer) { 190 napi_value retVal; 191 napi_value callback = nullptr; 192 void* data = nullptr; 193 napi_value arrayBuffer = nullptr; 194 size_t bufferSize = g_size; 195 napi_create_arraybuffer(env, bufferSize, &data, &arrayBuffer); 196 std::memcpy(data, copyBuffer, bufferSize); 197 OH_LOG_INFO(LOG_APP, "BufferCb g_size: %{public}zu", g_size); 198 napi_get_reference_value(env, bufferCbRef_, &callback); 199 if (callback) { 200 OH_LOG_INFO(LOG_APP, "BufferCb callback is full"); 201 } else { 202 OH_LOG_ERROR(LOG_APP, "BufferCb callback is null"); 203 } 204 // 调用ArkTS的buffer处理回调函数,将图片arrayBuffer传给页面做显示或保存。 205 napi_call_function(env, nullptr, callback, 1, &arrayBuffer, &retVal); 206 // 清理内存。 207 free(data); // 释放在异步工作中分配的内存。 208 }, 209 copyBuffer, &work); 210 211 // 错误检查:创建异步工作失败时释放内存。 212 if (status != napi_ok) { 213 OH_LOG_ERROR(LOG_APP, "Failed to create async work"); 214 free(copyBuffer); // 释放分配的内存。 215 return; 216 } 217 napi_queue_async_work_with_qos(env_, work, napi_qos_user_initiated); 218 } 219 220 // 保存ArkTS侧传入的buffer处理回调函数。 221 static napi_value SetBufferCb(napi_env env, napi_callback_info info) { 222 OH_LOG_INFO(LOG_APP, "SetBufferCb start"); 223 napi_value result; 224 napi_get_undefined(env, &result); 225 226 napi_value argValue[1] = {nullptr}; 227 size_t argCount = 1; 228 napi_get_cb_info(env, info, &argCount, argValue, nullptr, nullptr); 229 230 env_ = env; 231 napi_create_reference(env, argValue[0], 1, &bufferCbRef_); 232 if (bufferCbRef_) { 233 OH_LOG_INFO(LOG_APP, "SetBufferCb callbackRef is full"); 234 } else { 235 OH_LOG_ERROR(LOG_APP, "SetBufferCb callbackRef is null"); 236 } 237 // 注册ArkTS侧buffer回调到NAPI层。 238 RegisterBufferCb((void *)BufferCb); 239 return result; 240 } 241 ``` 242 2436. 创建拍照类型会话,参考[会话管理(C/C++)](./native-camera-session-management.md),开启会话,准备拍照。 244 2457. 配置拍照参数(可选)。 246 配置相机的参数可以调整拍照的一些功能,包括闪光灯、变焦、焦距等。 247 248 ```c++ 249 // 判断设备是否支持闪光灯。 250 bool HasFlash(Camera_CaptureSession* captureSession) 251 { 252 bool hasFlash = false; 253 Camera_ErrorCode ret = OH_CaptureSession_HasFlash(captureSession, &hasFlash); 254 if (ret != CAMERA_OK) { 255 OH_LOG_ERROR(LOG_APP, "OH_CaptureSession_HasFlash failed."); 256 } 257 if (hasFlash) { 258 OH_LOG_INFO(LOG_APP, "hasFlash success"); 259 } else { 260 OH_LOG_ERROR(LOG_APP, "hasFlash fail"); 261 } 262 return hasFlash; 263 } 264 265 // 检测闪光灯模式是否支持。 266 bool IsFlashModeSupported(Camera_CaptureSession* captureSession, Camera_FlashMode flashMode) 267 { 268 bool isSupported = false; 269 Camera_ErrorCode ret = OH_CaptureSession_IsFlashModeSupported(captureSession, flashMode, &isSupported); 270 if (ret != CAMERA_OK) { 271 OH_LOG_ERROR(LOG_APP, "OH_CaptureSession_IsFlashModeSupported failed."); 272 } 273 return isSupported; 274 } 275 // 在支持flashMode的情况下进行调用OH_CaptureSession_SetFlashMode。 276 Camera_ErrorCode SetFocusMode(Camera_CaptureSession* captureSession, Camera_FlashMode flashMode) 277 { 278 Camera_ErrorCode ret = OH_CaptureSession_SetFlashMode(captureSession, flashMode); 279 if (ret == CAMERA_OK) { 280 OH_LOG_INFO(LOG_APP, "OH_CaptureSession_SetFlashMode success."); 281 } else { 282 OH_LOG_ERROR(LOG_APP, "OH_CaptureSession_SetFlashMode failed. %{public}d ", ret); 283 } 284 return ret; 285 } 286 287 // 判断是否支持连续自动变焦模式。 288 bool IsFocusModeSupported(Camera_CaptureSession* captureSession, Camera_FocusMode focusMode) 289 { 290 bool isFocusModeSupported = false; 291 Camera_ErrorCode ret = OH_CaptureSession_IsFocusModeSupported(captureSession, focusMode, &isFocusModeSupported); 292 if (ret != CAMERA_OK) { 293 OH_LOG_ERROR(LOG_APP, "OH_CaptureSession_IsFocusModeSupported failed."); 294 } 295 return isFocusModeSupported; 296 } 297 // 在支持focusMode的情况下进行OH_CaptureSession_SetFocusMode。 298 Camera_ErrorCode SetFocusMode(Camera_CaptureSession* captureSession, Camera_FocusMode focusMode) 299 { 300 Camera_ErrorCode ret = OH_CaptureSession_SetFocusMode(captureSession, focusMode); 301 if (ret != CAMERA_OK) { 302 OH_LOG_ERROR(LOG_APP, "OH_CaptureSession_SetFocusMode failed. %{public}d ", ret); 303 } 304 return ret; 305 } 306 307 // 获取相机支持的可变焦距比范围。 308 Camera_ErrorCode GetZoomRatioRange(Camera_CaptureSession* captureSession, float* minZoom, float* maxZoom) 309 { 310 Camera_ErrorCode ret = OH_CaptureSession_GetZoomRatioRange(captureSession, minZoom, maxZoom); 311 if (ret != CAMERA_OK) { 312 OH_LOG_ERROR(LOG_APP, "OH_CaptureSession_GetZoomRatioRange failed."); 313 } else { 314 OH_LOG_INFO(LOG_APP, "OH_CaptureSession_GetZoomRatioRange success. minZoom: %{public}f, maxZoom:%{public}f", 315 *minZoom, *maxZoom); 316 } 317 return ret; 318 } 319 320 // 设置变焦,zoom需要在可变焦距比范围内。 321 Camera_ErrorCode SetZoomRatio(Camera_CaptureSession* captureSession, float zoom) 322 { 323 Camera_ErrorCode ret = OH_CaptureSession_SetZoomRatio(captureSession, zoom); 324 if (ret == CAMERA_OK) { 325 OH_LOG_INFO(LOG_APP, "OH_CaptureSession_SetZoomRatio success."); 326 } else { 327 OH_LOG_ERROR(LOG_APP, "OH_CaptureSession_SetZoomRatio failed. %{public}d ", ret); 328 } 329 return ret; 330 } 331 ``` 332 3338. 触发拍照。 334 335 通过[OH_PhotoOutput_Capture()](../../reference/apis-camera-kit/_o_h___camera.md#oh_photooutput_capture)方法,执行拍照任务。 336 337 ```c++ 338 Camera_ErrorCode Capture(Camera_PhotoOutput* photoOutput) 339 { 340 Camera_ErrorCode ret = OH_PhotoOutput_Capture(photoOutput); 341 if (ret == CAMERA_OK) { 342 OH_LOG_INFO(LOG_APP, "OH_PhotoOutput_Capture success "); 343 } else { 344 OH_LOG_ERROR(LOG_APP, "OH_PhotoOutput_Capture failed. %d ", ret); 345 } 346 return ret; 347 } 348 ``` 349 350## 状态监听 351 352在相机应用开发过程中,可以随时监听拍照输出流状态,包括拍照流开始、拍照帧的开始与结束、拍照输出流的错误。 353 354- 通过注册固定的onFrameStart回调函数获取监听拍照开始结果,photoOutput创建成功时即可监听,拍照第一次曝光时触发。 355 ```c++ 356 void PhotoOutputOnFrameStart(Camera_PhotoOutput* photoOutput) 357 { 358 OH_LOG_INFO(LOG_APP, "PhotoOutputOnFrameStart"); 359 } 360 void PhotoOutputOnFrameShutter(Camera_PhotoOutput* photoOutput, Camera_FrameShutterInfo* info) 361 { 362 OH_LOG_INFO(LOG_APP, "PhotoOutputOnFrameShutter"); 363 } 364 ``` 365 366- 通过注册固定的onFrameEnd回调函数获取监听拍照结束结果,photoOutput创建成功时即可监听。 367 368 ```c++ 369 void PhotoOutputOnFrameEnd(Camera_PhotoOutput* photoOutput, int32_t frameCount) 370 { 371 OH_LOG_INFO(LOG_APP, "PhotoOutput frameCount = %{public}d", frameCount); 372 } 373 ``` 374 375- 通过注册固定的onError回调函数获取监听拍照输出流的错误结果。callback返回拍照输出接口使用错误时的对应错误码,错误码类型参见[Camera_ErrorCode](../../reference/apis-camera-kit/_o_h___camera.md#camera_errorcode-1)。 376 377 ```c++ 378 void PhotoOutputOnError(Camera_PhotoOutput* photoOutput, Camera_ErrorCode errorCode) 379 { 380 OH_LOG_INFO(LOG_APP, "PhotoOutput errorCode = %{public}d", errorCode); 381 } 382 ``` 383 ```c++ 384 PhotoOutput_Callbacks* GetPhotoOutputListener() 385 { 386 static PhotoOutput_Callbacks photoOutputListener = { 387 .onFrameStart = PhotoOutputOnFrameStart, 388 .onFrameShutter = PhotoOutputOnFrameShutter, 389 .onFrameEnd = PhotoOutputOnFrameEnd, 390 .onError = PhotoOutputOnError 391 }; 392 return &photoOutputListener; 393 } 394 Camera_ErrorCode RegisterPhotoOutputCallback(Camera_PhotoOutput* photoOutput) 395 { 396 Camera_ErrorCode ret = OH_PhotoOutput_RegisterCallback(photoOutput, GetPhotoOutputListener()); 397 if (ret != CAMERA_OK) { 398 OH_LOG_ERROR(LOG_APP, "OH_PhotoOutput_RegisterCallback failed."); 399 } 400 return ret; 401 } 402 ```