← 返回首页
多媒体

📷 Camera 相机

完整的相机应用示例,支持拍照、录像、分辨率设置、旋转角度调整等功能

API级别: API 9+ | 项目路径: HarmonyOS_NEXT/Media/Camera

📋 项目简介

Camera示例是一个功能完整的相机应用,展示HarmonyOS的多媒体相机API使用方法。

核心功能

💻 核心代码示例

1. 引入相机模块

import camera from '@ohos.multimedia.camera';
import prompt from '@ohos.promptAction';

2. 初始化相机

private cameraModel: CameraModel = new CameraModel();
private mXComponentController: XComponentController = new XComponentController();

async aboutToAppear() {
  // 申请权限
  await grantPermission();
  
  // 获取surfaceId
  this.surfaceId = this.mXComponentController.getXComponentSurfaceId();
  
  // 初始化相机
  this.cameraModel.initCamera(this.surfaceId);
}

3. XComponent 相机预览

XComponent({
  id: 'componentId',
  type: 'surface',  // 必须设置为surface
  controller: this.mXComponentController
})
.onLoad(() => {
  this.mXComponentController.setXComponentSurfaceSize({ 
    surfaceWidth: 640, 
    surfaceHeight: 480 
  });
  this.surfaceId = this.mXComponentController.getXComponentSurfaceId();
  this.cameraModel.initCamera(this.surfaceId);
})
.width('100%')
.height('100%')

4. 拍照

photoEvent() {
  if (this.currentModel === CameraMode.modePhoto) {
    prompt.showToast({ message: '拍照中...', duration: 200 });
    this.cameraModel.takePicture();
  }
}

5. 录像

videoEvent() {
  if (!this.isRecording) {
    this.timeShow = true;
    this.textTimerController.reset();
    this.textTimerController.start();
    this.cameraModel.startVideo();
    this.isRecording = true;
  } else {
    this.timeShow = false;
    this.textTimerController.pause();
    this.cameraModel.stopVideo();
    this.isRecording = false;
  }
}

🔧 核心API

API说明
camera.getCameraManager()获取相机管理器
getSupportedCameras()获取支持的相机列表
createPreviewOutput()创建预览输出
createPhotoOutput()创建拍照输出
createVideoOutput()创建视频输出
takePicture()拍照
startVideo()/stopVideo()开始/停止录像
cameraRelease()释放相机资源

🔐 权限配置

// module.json5
{
  "module": {
    "requestPermissions": [
      {
        "name": "ohos.permission.CAMERA"
      },
      {
        "name": "ohos.permission.MICROPHONE"
      },
      {
        "name": "ohos.permission.WRITE_MEDIA"
      }
    ]
  }
}

⚠️ 注意事项

• 权限必须动态申请,不能只在配置文件中声明

• 页面退出时必须释放相机资源

• surfaceId需要在XComponent的onLoad回调中获取

• 需要考虑不同设备的相机能力差异

🔗 参考资料

📎 官方仓库链接