鸿蒙Next中ArkUI如何调用相机拍照
在鸿蒙Next的ArkUI框架中,如何实现调用设备相机进行拍照功能?需要具体代码示例说明如何初始化相机、配置参数、捕获图像以及保存照片。官方文档中提到的相关API该如何正确使用?
2 回复
在鸿蒙Next的ArkUI中,可以通过@ohos.multimedia.camera和@ohos.multimedia.image模块调用相机拍照。以下是实现步骤和示例代码:
1. 申请权限
在module.json5中添加相机和存储权限:
{
"module": {
"requestPermissions": [
{
"name": "ohos.permission.CAMERA"
},
{
"name": "ohos.permission.WRITE_IMAGEVIDEO"
}
]
}
}
2. ArkTS代码实现
import camera from '@ohos.multimedia.camera';
import image from '@ohos.multimedia.image';
import fs from '@ohos.file.fs';
import { BusinessError } from '@ohos.base';
@Entry
@Component
struct CameraPage {
// 相机管理器
private cameraManager: camera.CameraManager | null = null;
private cameraInput: camera.CameraInput | null = null;
private previewOutput: camera.PreviewOutput | null = null;
private photoOutput: camera.PhotoOutput | null = null;
// 预览Surface
private previewSurfaceId: string = '';
async aboutToAppear() {
await this.initCamera();
}
// 初始化相机
async initCamera() {
try {
// 1. 获取CameraManager
this.cameraManager = camera.getCameraManager();
// 2. 获取相机设备列表
const cameras = this.cameraManager.getSupportedCameras();
if (cameras.length === 0) return;
// 3. 创建相机输入流
this.cameraInput = this.cameraManager.createCameraInput(cameras[0]);
await this.cameraInput.open();
// 4. 创建预览输出
this.previewSurfaceId = await this.createPreviewSurface();
this.previewOutput = this.cameraManager.createPreviewOutput(
this.previewSurfaceId
);
// 5. 创建拍照输出
this.photoOutput = this.cameraManager.createPhotoOutput();
// 6. 创建会话并配置
const session = this.cameraManager.createSession();
session.beginConfig();
session.addInput(this.cameraInput);
session.addOutput(this.previewOutput);
session.addOutput(this.photoOutput);
await session.commitConfig();
await session.start();
} catch (error) {
console.error('Camera init failed: ' + (error as BusinessError).message);
}
}
// 创建预览Surface
private async createPreviewSurface(): Promise<string> {
// 实际开发中需要XComponent来显示预览
// 这里返回模拟的surfaceId
return 'preview_surface';
}
// 拍照功能
takePhoto() {
if (!this.photoOutput) return;
const photoSettings: camera.PhotoSettings = {
rotation: camera.ImageRotation.ROTATION_0,
quality: camera.QualityLevel.QUALITY_LEVEL_HIGH
};
this.photoOutput.capture(photoSettings, (err: BusinessError) => {
if (err) {
console.error('Photo capture failed: ' + err.message);
} else {
console.info('Photo captured successfully');
}
});
}
build() {
Column() {
// 预览画面区域(需要配合XComponent)
// XComponent({ id: 'preview', type: 'surface' })
Button('拍照')
.onClick(() => {
this.takePhoto();
})
}
}
aboutToDisappear() {
// 释放资源
this.cameraInput?.close();
}
}
关键说明:
- 权限管理:必须申请相机和存储权限
- 预览显示:实际使用时需要配合
XComponent组件显示相机预览 - 资源释放:页面销毁时需要关闭相机输入
- 错误处理:所有操作都需要添加异常捕获
注意事项:
- 需要真机测试,模拟器不支持相机功能
- 照片保存路径需要根据实际需求配置
- 建议在页面生命周期中管理相机资源
这个示例展示了基本的相机调用和拍照流程,实际开发中还需要处理预览显示、照片保存等具体逻辑。


