使用CameraPicker拉起系统相机
如何调用系统拍照并获取图片-相机开发(Camera)-拍照和图片-媒体开发-开发 - 华为HarmonyOS开发者
CommonConstants
export class CommonConstants {
/**
* Size of components.
*/
static readonly FULL_SIZE: string = '100%';
}
ImagePickerPage
import { cameraPicker } from '@kit.CameraKit';
import { camera } from '@kit.CameraKit';
import { BusinessError } from '@ohos.base';
import { hilog } from '@kit.PerformanceAnalysisKit'
import { CommonConstants as Const } from '../common/constants/CommonConstants';
@Entry
@Component
struct ImagePickerPage {
@State uri: Resource | string | undefined = undefined;
private cameraPosition: Array<camera.CameraPosition> = [
camera.CameraPosition.CAMERA_POSITION_UNSPECIFIED, camera.CameraPosition.CAMERA_POSITION_BACK,
camera.CameraPosition.CAMERA_POSITION_FRONT, camera.CameraPosition.CAMERA_POSITION_FOLD_INNER
];
private mediaType: Array<cameraPicker.PickerMediaType> = [
cameraPicker.PickerMediaType.PHOTO, cameraPicker.PickerMediaType.VIDEO
];
build() {
Row() {
Column() {
Image(this.uri)
.height($r('app.float.image_height'))
.alt($r('app.media.startIcon'))
Button($r('app.string.capture'))
.width($r('app.float.button_width'))
.margin({ top: $r('app.float.margin') })
.onClick(async () => {
try {
// Configure to launch the rear camera
let pickerProfile: cameraPicker.PickerProfile = { cameraPosition: this.cameraPosition[1] };
// Configure to photo mode
let pickerResult: cameraPicker.PickerResult = await cameraPicker.pick(getContext(this),
[this.mediaType[0]], pickerProfile);
// Get video URI
this.uri = pickerResult.resultUri;
hilog.info(0x0000, ' ', "the pick pickerResult is:" + JSON.stringify(pickerResult));
// the pick pickerResult is:{"resultCode":0,"resultUri":"file://media/Photo/24/IMG_1741153812_023/IMG_20250305_134832.jpg","mediaType":"photo"}
} catch (error) {
let err = error as BusinessError;
hilog.error(0x0000, '', `the pick call failed. error code: ${err.code}`);
}
})
}
.width(Const.FULL_SIZE)
}
.height(Const.FULL_SIZE)
}
}