HarmonyOS 关于相机选择器组件增加自动保存到相册配置的需求

在有些业务场景下会使用公共设备,对拍摄的图片和视频不保存到相册,目前cameraPicker (相机选择器)组件拍照或录制后的图片和视频会自动保存到相册,可否增加一个API来配置是否自动保存?

https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-camerapicker-V5#pick

HarmonyOS
1天前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
Excelsior_abit

请参考示例如下:

index.ets

import camera from '@ohos.multimedia.camera';
import image from '@ohos.multimedia.image';
import { BusinessError } from '@ohos.base';
import common from '@ohos.app.ability.common';
import fs from '@ohos.file.fs';
import PhotoAccessHelper from '@ohos.file.photoAccessHelper';
import { abilityAccessCtrl, bundleManager, Permissions } from '@kit.AbilityKit';
import { GlobalContext } from '../utils/GlobalContext';
import commonEvent from '@ohos.commonEvent';
import Logger from '../utils/Logger';
import photoAccessHelper from '@ohos.file.photoAccessHelper';

let photoOutput: camera.PhotoOutput;
let cameraInput: camera.CameraInput | undefined = undefined;
let previewOutput: camera.PreviewOutput | undefined = undefined;
//创建会话
let photoSession: camera.CaptureSession | undefined = undefined;
let context = getContext(this);
let TAG: string = ""cameraAPI11"";
let context1 = getContext() as common.BaseContext;
let cameraWidth = 1920;
let cameraHeight = 1080;
let arrayBuffer:ArrayBuffer;
// let photoOutput: camera.PhotoOutput | undefined = undefined;
@Entry
@Component
struct Index {
  @State message: string = 'Hello World';
  mXComponentController: XComponentController = new XComponentController;
  surfaceId: string = '';
  @State saveButtonOptions: SaveButtonOptions = {
    icon: SaveIconStyle.FULL_FILLED,
    text: SaveDescription.SAVE_IMAGE,
    buttonType: ButtonType.Capsule
  } // 设置安全控件按钮属性
  async onPageShow() {
    await grantPermission().then(res => {
      console.info(TAG, `权限申请成功  ${JSON.stringify(res)}`);
      if (res) {
        cameraShootingCase(context1,this.surfaceId)
      }
    })
  }

  aboutToDisappear(): void {
    release();
  }

  build() {
    Row() {
      Column() {
        XComponent({
          id: '',
          type: 'surface',
          libraryname: '',
          controller: this.mXComponentController
        })
          .height('70%')
          .onLoad(() => {
            // 设置Surface宽高(1920*1080),预览尺寸设置参考前面 previewProfilesArray 获取的当前设备所支持的预览分辨率大小去设置
            // 预览流与录像输出流的分辨率的宽高比要保持一致
            this.mXComponentController.setXComponentSurfaceSize({surfaceWidth:cameraWidth,surfaceHeight:cameraHeight});
            // 获取Surface ID
            this.surfaceId = this.mXComponentController.getXComponentSurfaceId();
          })

        Button('photo')
          .onClick((event: ClickEvent) => {
            let settings: camera.PhotoCaptureSetting = {
              quality: camera.QualityLevel.QUALITY_LEVEL_HIGH,  // 设置图片质量高
              rotation: camera.ImageRotation.ROTATION_0,  // 设置图片旋转角度0
              mirror: false  // 设置镜像使能开关(默认关)
            };
            photoOutput.capture(settings, (err: BusinessError) => {
              if (err) {
                console.error(`Failed to capture the photo. error: ${JSON.stringify(err)}`);
                return;
              }
              console.info('Callback invoked to indicate the photo capture request success.');
            });
          })
        SaveButton(this.saveButtonOptions) // 创建安全控件按钮
          .padding(5)
          .onClick(async (event, result: SaveButtonOnClickResult) => {
            if (result == SaveButtonOnClickResult.SUCCESS) {
              try {
                let context = getContext();
                let phAccessHelper = photoAccessHelper.getPhotoAccessHelper(context);
                let uri = await phAccessHelper.createAsset(photoAccessHelper.PhotoType.IMAGE, 'jpg'); // 创建媒体文件
                console.info('createAsset successfully, uri: ' + uri);
                let file = await fs.open(uri, fs.OpenMode.READ_WRITE|| fs.OpenMode.CREATE);
                await fs.write(file.fd, arrayBuffer);
                await fs.close(file);
              } catch (err) {
                console.error('createAsset failed, message = ', err);
              }
            } else {
              console.error('SaveButtonOnClickResult createAsset failed');
            }
          })
      }
      .width('100%')
    }
    .height('100%')
  }
}
async function savePicture(buffer: ArrayBuffer, img: image.Image) {
  arrayBuffer=buffer;
  img.release();
}

function setPhotoOutputCb(photoOutput: camera.PhotoOutput) {
  //设置回调之后,调用photoOutput的capture方法,就会将拍照的buffer回传到回调中
  photoOutput.on('photoAvailable', (errCode: BusinessError, photo: camera.Photo): void => {
    console.info('getPhoto start');
    console.info(`err: ${JSON.stringify(errCode)}`);
    if (errCode || photo === undefined) {
      console.error('getPhoto failed');
      return;
    }
    let imageObj = photo.main;
    imageObj.getComponent(image.ComponentType.JPEG, (errCode: BusinessError, component: image.Component): void => {
      console.info('getComponent start');
      if (errCode || component === undefined) {
        console.error('getComponent failed');
        return;
      }
      let buffer: ArrayBuffer;
      if (component.byteBuffer) {
        buffer = component.byteBuffer;
      } else {
        console.error('byteBuffer is null');
        return;
      }
      savePicture(buffer, imageObj);
    });
  });
}
function release(){
  if(photoSession){
    // 停止当前会话
    //调用Session.stop方法停止输出metadata数据,接口调用失败会返回相应错误码,错误码类型参见Camera错误码。
    photoSession.stop();
  }
  if(cameraInput){
    // 释放相机输入流
    cameraInput.close();
  }
  if(previewOutput){
    // 释放预览输出流
    previewOutput.release();
  }
  if(photoSession){
    // 释放会话
    photoSession.release();
    // 会话置空
    photoSession = undefined;
  }
}
function onMetadataError(metadataOutput: camera.MetadataOutput): void {
  metadataOutput.on('error', (metadataOutputError: BusinessError) => {
    console.error(`Metadata output error code: ${metadataOutputError.code}`);
  });
}
function onMetadataObjectsAvailable(metadataOutput: camera.MetadataOutput): void {
  metadataOutput.on('metadataObjectsAvailable', (err: BusinessError, metadataObjectArr: Array<camera.MetadataObject>) => {
    console.info('metadata output metadataObjectsAvailable');
    console.info('metadata output metadataObjectsAvailable66:'+JSON.stringify(metadataObjectArr[0].boundingBox));
  });
}
async function cameraShootingCase(baseContext: common.BaseContext, surfaceId: string): Promise<void> {
  // 创建CameraManager对象
  let cameraManager: camera.CameraManager = camera.getCameraManager(baseContext);
  if (!cameraManager) {
    console.error(""camera.getCameraManager error"");
    return;
  }
  // 监听相机状态变化
  cameraManager.on('cameraStatus', (err: BusinessError, cameraStatusInfo: camera.CameraStatusInfo) => {
    console.info(`camera : ${cameraStatusInfo.camera.cameraId}`);
    console.info(`status: ${cameraStatusInfo.status}`);
  });

  // 获取相机列表
  let cameraArray: Array<camera.CameraDevice> = cameraManager.getSupportedCameras();
  if (cameraArray.length <= 0) {
    console.error(""cameraManager.getSupportedCameras error"");
    return;
  }

  for (let index = 0; index < cameraArray.length; index++) {
    console.info('cameraId : ' + cameraArray[index].cameraId);                          // 获取相机ID
    console.info('cameraPosition : ' + cameraArray[index].cameraPosition);              // 获取相机位置
    console.info('cameraType : ' + cameraArray[index].cameraType);                      // 获取相机类型
    console.info('connectionType : ' + cameraArray[index].connectionType);              // 获取相机连接类型
  }

  // 创建相机输入流
  try {
    cameraInput = cameraManager.createCameraInput(cameraArray[0]);
  } catch (error) {
    let err = error as BusinessError;
    console.error('Failed to createCameraInput errorCode = ' + err.code);
  }
  if (cameraInput === undefined) {
    return;
  }

  // 监听cameraInput错误信息
  let cameraDevice: camera.CameraDevice = cameraArray[0];
  cameraInput.on('error', cameraDevice, (error: BusinessError) => {
    console.error(`Camera input error code: ${error.code}`);
  })

  // 打开相机
  await cameraInput.open();

  //获取支持的模式类型
  let sceneModes: Array<camera.SceneMode> = cameraManager.getSupportedSceneModes(cameraArray[0]);
  let isSupportPhotoMode: boolean = sceneModes.indexOf(camera.SceneMode.NORMAL_PHOTO) >= 0;
  if (!isSupportPhotoMode) {
    console.error('photo mode not support');
    return;
  }
  //获取相机设备支持的输出流能力
  let cameraOutputCap: camera.CameraOutputCapability = cameraManager.getSupportedOutputCapability(cameraArray[0], camera.SceneMode.NORMAL_PHOTO);
  if (!cameraOutputCap) {
    console.error(""cameraManager.getSupportedOutputCapability error"");
    return;
  }
  console.info(""outputCapability: "" + JSON.stringify(cameraOutputCap));
  let metadataObjectTypes: Array<camera.MetadataObjectType> = cameraOutputCap.supportedMetadataObjectTypes;
  let metadataOutput: camera.MetadataOutput | undefined = undefined;
  try {
    metadataOutput = cameraManager.createMetadataOutput(metadataObjectTypes);
    onMetadataObjectsAvailable(metadataOutput);
    onMetadataError(metadataOutput);
  } catch (error) {
    let err = error as BusinessError;
    console.error(`Failed to createMetadataOutput, error code: ${err.code}`);
  }

  let previewProfilesArray: Array<camera.Profile> = cameraOutputCap.previewProfiles;
  if (!previewProfilesArray) {
    console.error(""createOutput previewProfilesArray == null || undefined"");
  }
  let previewProfilesObj: camera.Profile = previewProfilesArray[0];
  previewProfilesArray.forEach(profile => {
    let supportSize = profile.size
    Logger.debug(""----choose Supported profile: size1-- "" + supportSize.width + "" "" + supportSize.height + "" type:"" + profile.format)
    if (supportSize.width == cameraWidth && supportSize.height == cameraHeight
    // && profile.format==camera.CameraFormat.CAMERA_FORMAT_YUV_420_SP
    ) {
      // 选择1920x1080的profile
      previewProfilesObj = profile;

      Logger.debug(""----choose Supported profile: size-- "" + supportSize.width + "" "" + supportSize.height + "" type:"" + profile.format)
    }
    Logger.debug(""Supported profile: size-- "" + supportSize.width + "" "" + supportSize.height + "" type:"" + profile.format)
  });
  
  let photoProfilesArray: Array<camera.Profile> = cameraOutputCap.photoProfiles;
  if (!photoProfilesArray) {
    console.error(""createOutput photoProfilesArray == null || undefined"");
  }
  // 创建预览输出流,其中参数 surfaceId 参考上文 XComponent 组件,预览流为XComponent组件提供的surface
  try {
    previewOutput = cameraManager.createPreviewOutput(previewProfilesObj, surfaceId);
  } catch (error) {
    let err = error as BusinessError;
    console.error(`Failed to create the PreviewOutput instance. error code: ${err.code}`);
  }
  if (previewOutput === undefined) {
    return;
  }
  // 监听预览输出错误信息
  previewOutput.on('error', (error: BusinessError) => {
    console.error(`Preview output error code: ${error.code}`);
  });

  // 创建拍照输出流
  try {
    photoOutput = cameraManager.createPhotoOutput(photoProfilesArray[0]);
  } catch (error) {
    let err = error as BusinessError;
    console.error('Failed to createPhotoOutput errorCode = ' + err.code);
  }
  if (photoOutput === undefined) {
    return;
  }
  //调用上面的回调函数来保存图片
  setPhotoOutputCb(photoOutput);
  try {
    photoSession = cameraManager.createCaptureSession();
  } catch (error) {
    let err = error as BusinessError;
    console.error('Failed to create the session instance. errorCode = ' + err.code);
  }
  if (photoSession === undefined) {
    return;
  }
  // 监听session错误信息
  photoSession.on('error', (error: BusinessError) => {
    console.error(`Capture session error code: ${error.code}`);
  });

  // 开始配置会话
  try {
    photoSession.beginConfig();
  } catch (error) {
    let err = error as BusinessError;
    console.error('Failed to beginConfig. errorCode = ' + err.code);
  }

  // 向会话中添加相机输入流
  try {
    photoSession.addInput(cameraInput);
  } catch (error) {
    let err = error as BusinessError;
    console.error('Failed to addInput. errorCode = ' + err.code);
  }

  // 向会话中添加预览输出流
  try {
    photoSession.addOutput(previewOutput);
  } catch (error) {
    let err = error as BusinessError;
    console.error('Failed to addOutput(previewOutput). errorCode = ' + err.code);
  }
  try {
    photoSession.addOutput(metadataOutput);
  } catch (error) {
    let err = error as BusinessError;
    console.error('Failed to addOutput(metadataOutput).errorCode = ' + err.code);
  }
  // 向会话中添加拍照输出流
  try {
    photoSession.addOutput(photoOutput);
  } catch (error) {
    let err = error as BusinessError;
    console.error('Failed to addOutput(photoOutput). errorCode = ' + err.code);
  }

  // 提交会话配置
  await photoSession.commitConfig();

  // 启动会话
  await photoSession.start().then(() => {
    console.info('Promise returned to indicate the session start success.');
  });
  configuringSession(photoSession);
}
function configuringSession(photoSession: camera.CaptureSession): void {
  // 判断设备是否支持闪光灯
  let flashStatus: boolean = false;
  try {
    flashStatus = photoSession.hasFlash();
  } catch (error) {
    let err = error as BusinessError;
    console.error(`Failed to hasFlash. error: ${JSON.stringify(err)}`);
  }
  console.info(`Returned with the flash light support status: ${flashStatus}`);
  if (flashStatus) {
    // 判断是否支持自动闪光灯模式
    let flashModeStatus: boolean = false;
    try {
      let status: boolean = photoSession.isFlashModeSupported(camera.FlashMode.FLASH_MODE_AUTO);
      flashModeStatus = status;
    } catch (error) {
      let err = error as BusinessError;
      console.error(`Failed to check whether the flash mode is supported. error: ${JSON.stringify(err)}`);
    }
    if (flashModeStatus) {
      // 设置自动闪光灯模式
      try {
        photoSession.setFlashMode(camera.FlashMode.FLASH_MODE_AUTO);
      } catch (error) {
        let err = error as BusinessError;
        console.error(`Failed to set the flash mode. error: ${JSON.stringify(err)}`);
      }
    }
  }
  // 判断是否支持连续自动变焦模式
  let focusModeStatus: boolean = false;
  try {
    let status: boolean = photoSession.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO);
    focusModeStatus = status;
  } catch (error) {
    let err = error as BusinessError;
    console.error(`Failed to check whether the focus mode is supported. error: ${JSON.stringify(err)}`);
  }
  if (focusModeStatus) {
    // 设置连续自动变焦模式
    try {
      photoSession.setFocusMode(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO);
    } catch (error) {
      let err = error as BusinessError;
      console.error(`Failed to set the focus mode. error: ${JSON.stringify(err)}`);
    }
  }
  // 获取相机支持的可变焦距比范围
  let zoomRatioRange: Array<number> = [];
  try {
    zoomRatioRange = photoSession.getZoomRatioRange();
  } catch (error) {
    let err = error as BusinessError;
    console.error(`Failed to get the zoom ratio range. error: ${JSON.stringify(err)}`);
  }
  if (zoomRatioRange.length <= 0 ) {
    return;
  }
  // 设置可变焦距比
  try {
    photoSession.setZoomRatio(zoomRatioRange[0]);
  } catch (error) {
    let err = error as BusinessError;
    console.error(`Failed to set the zoom ratio value. error: ${JSON.stringify(err)}`);
  }
}

async function grantPermission(): Promise<boolean> {
  const PERMISSIONS: Array<Permissions> = [
    'ohos.permission.CAMERA',
  ];
  try {
    // 获取应用程序的accessTokenID
    let bundleInfo: bundleManager.BundleInfo =
      await bundleManager.getBundleInfoForSelf(
        bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION
      );
    let appInfo: bundleManager.ApplicationInfo = bundleInfo.appInfo;
    let tokenId = appInfo.accessTokenId;
    let atManager = abilityAccessCtrl.createAtManager();
    let pems: Array<Permissions> = [];
    for (let i = 0; i < PERMISSIONS.length; i++) {
      let state = await atManager.checkAccessToken(tokenId, PERMISSIONS[i]);
      console.info(TAG, `grantPermission  checkAccessToken ${PERMISSIONS[i]} + : ${JSON.stringify(state)}`);
      if (state !== abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) {
        pems.push(PERMISSIONS[i]);
      }
    }
    if (pems.length > 0) {
      console.info(TAG, 'grantPermission  requestPermissionsFromUser :' + JSON.stringify(pems));
      let result = await atManager.requestPermissionsFromUser(GlobalContext.get().getCameraAbilityContext(), pems);
      let grantStatus: Array<number> = result.authResults;
      let length: number = grantStatus.length;
      for (let i = 0; i < length; i++) {
        // console.info(TAG, `grantPermission  requestPermissionsFromUser ${result.permissions[i]} + : ${grantStatus[i]}`);

        if (grantStatus[i] === 0) {
          // 用户授权,可以继续访问目标操作
        } else {
          // 用户拒绝授权,提示用户必须授权才能访问当前页面的功能
          console.log(TAG + 'grantPermission  fail ');
          return false;
        }
      }
    }
    // 授权成功
    console.info(TAG, 'grantPermission  success ');
    return true;
  } catch (e) {
    console.info(TAG, 'grantPermission  fail ');
    return false;
  }
}

GlobalContext.ts

export class GlobalContext {
  private static TAG: string = '[GlobalContext]:';
  private static instance: GlobalContext;
  private cameraAbilityContext;

  private constructor() {
  }

  public static get(): GlobalContext {
    if (!Boolean(GlobalContext.instance).valueOf()) {
      GlobalContext.instance = new GlobalContext();
    }
    return GlobalContext.instance;
  }

  public getCameraAbilityContext() {
    return this.cameraAbilityContext;
  }

  public setCameraAbilityContext(context): void {
    this.cameraAbilityContext = context;
  }
}

Logger.ets

import hilog from '@ohos.hilog';

class Logger {
  private domain: number;
  private prefix: string;
  private format: string = '%{public}s, %{public}s';
  private showLog = true;

  constructor(prefix: string) {
    this.prefix = prefix;
    this.domain = 0xff00;
  }

  needLog(needShow:boolean){
    this.showLog = needShow;
  }

  debug(...args: string[]): void {
    if(!this.showLog)return;
    hilog.debug(this.domain, this.prefix, this.format, args);
  }

  info(...args: string[]): void {
    if(!this.showLog)return;
    hilog.info(this.domain, this.prefix, this.format, args);
  }

  warn(...args: string[]): void {
    if(!this.showLog)return;
    hilog.warn(this.domain, this.prefix, this.format, args);
  }
分享
微博
QQ
微信
回复
1天前
相关问题
HarmonyOS 有没有保存到相册组件
40浏览 • 1回复 待解决
HarmonyOS 图片保存到相册报错
62浏览 • 1回复 待解决
HarmonyOS 保存到相册报错13900012
60浏览 • 1回复 待解决
HarmonyOS如何将PixelMap保存到相册
613浏览 • 1回复 待解决
HarmonyOS图片选择器相关问题
506浏览 • 1回复 待解决
HarmonyOS 图片选择器怎么实现
83浏览 • 1回复 待解决
js相机组件拍照后自动保存
4193浏览 • 1回复 待解决
HarmonyOS 有状态选择器
45浏览 • 1回复 待解决
获取网络图片并保存到相册
1534浏览 • 1回复 待解决
HarmonyOS如何把图片保存到手机相册
549浏览 • 1回复 待解决
HarmonyOS 地区选择器多级列表效果
418浏览 • 1回复 待解决
HarmonyOS web如何拉起图库选择器
48浏览 • 1回复 待解决