参考demo:import picker from '@ohos.multimedia.cameraPicker' import camera from '@ohos.multimedia.camera'; import common from '@ohos.app.ability.common'; import { BusinessError } from '@ohos.base'; import fileuri from '@ohos.file.fileuri'; import fs from '@ohos.file.fs'; let mContext = getContext(this) as common.Context; class CameraPosition { cameraPosition : camera.CameraPosition saveUri :string constructor(cameraPosition : camera.CameraPosition,saveUri:string) { this.cameraPosition = cameraPosition this.saveUri = saveUri } } let pathDir = getContext().filesDir; let filePath = pathDir + `/${new Date().getTime()}.jpg}` fs.createRandomAccessFileSync(filePath, fs.OpenMode.CREATE); let uri = fileuri.getUriFromPath(filePath); async function demo() { try { let pickerProfile = new CameraPosition(camera.CameraPosition.CAMERA_POSITION_BACK,uri) //前置摄像机传CAMERA_POSITION_FRONT,后置摄像机传CAMERA_POSITION_BACK,saveuri传想存到对应沙箱的uri let pickerResult: picker.PickerResult = await picker.pick(mContext, [picker.PickerMediaType.PHOTO, picker.PickerMediaType.VIDEO], pickerProfile); console.log("the pick pickerResult is:" + JSON.stringify(pickerResult)); } catch (error) { let err = error as BusinessError; console.error(`the pick call failed. error code: ${err.code}`); } } @Entry @Component struct IndexPage{ build(){ Column(){ Button('拉起后置摄像头').onClick(()=>{ demo() }) } } }照片不存相册可参照:const context2 = getContext(this); const imageSourceApi: image.ImageSource = image.createImageSource(this.combinePath); let packOpts: image.PackingOption = { format: "image/jpeg", quality: 98 }; const filePath: string = context2.filesDir + "/image_source.jpg"; let file2 = fs.openSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE); const imagePackerApi: image.ImagePacker = image.createImagePacker(); imagePackerApi.packToFile(imageSourceApi, file2.fd, packOpts, (err: BusinessError) => { if (err) { console.error(`Failed to pack the image to file.code ${err.code},message is ${err.message}`); } else { console.info('Succeeded in packing the image to file.'); } })
参考demo:
照片不存相册可参照: