HarmonyOS 应用拍摄的图片如何只保存在沙箱中,不保存在系统相册中

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

参考保存到沙箱路径demo:

import { BusinessError } from '@kit.BasicServicesKit';
import { camera } from '@kit.CameraKit';
import { abilityAccessCtrl, common } from '@kit.AbilityKit';
import { image } from '@kit.ImageKit';
import fs from '@ohos.file.fs';
import promptAction from '@ohos.promptAction';

const context = getContext(this) as common.UIAbilityContext;
@Entry
@Component
struct GetFrontCameraImage {
  private xComponentController: XComponentController = new XComponentController();

  private previewOutput?: camera.PreviewOutput
  private photoOutput?: camera.PhotoOutput
  @State pixmap?: image.PixelMap = undefined
  private buffer: ArrayBuffer | undefined = undefined
  async getCameraImage() {
    // 1、使用系统相机框架camera模块获取物理摄像头信息。
    let cameraManager = camera.getCameraManager(context);
    let camerasInfo: Array<camera.CameraDevice> = cameraManager.getSupportedCameras();
    let cameraDevice: camera.CameraDevice = camerasInfo[0];
    // 检测相机状态
    cameraManager.on('cameraStatus', (err: BusinessError, cameraStatusInfo: camera.CameraStatusInfo) => {
      console.log(`camera : ${cameraStatusInfo.camera.cameraId}`);
      console.log(`status : : ${cameraStatusInfo.status}`);
    });
    // 2、创建并启动物理摄像头输入流通道
    // 设置为前置摄像头 camera.CameraPosition.CAMERA_POSITION_FRONT
    let cameraInput = cameraManager.createCameraInput(camera.CameraPosition.CAMERA_POSITION_BACK, camera.CameraType.CAMERA_TYPE_DEFAULT);
    await cameraInput.open();
    // 3、拿到物理摄像头信息查询摄像头支持预览流支持的输出格式,结合XComponent提供的surfaceId创建预览输出通道
    let outputCapability = cameraManager.getSupportedOutputCapability(cameraDevice, camera.SceneMode.NORMAL_PHOTO);
    let previewProfile = outputCapability.previewProfiles[0];
    let surfaceId = this.xComponentController.getXComponentSurfaceId();
    this.previewOutput = cameraManager.createPreviewOutput(previewProfile, surfaceId);

    this.photoOutput = cameraManager!.createPhotoOutput(outputCapability.photoProfiles[0]);
    this.photoOutput!.on('photoAvailable', (errCode: BusinessError, photo: camera.Photo): void => {
      if (errCode) {
        console.error(`${errCode}`)
      }
      let imageObj = photo.main;
      imageObj.getComponent(image.ComponentType.JPEG, async (errCode: BusinessError, component: image.Component) => {
        if (errCode || component === undefined) {
          return;
        }
        if (component.byteBuffer) {
          this.buffer = component.byteBuffer;
          console.log("buffer::"+this.buffer.byteLength)
          if (component.byteBuffer as ArrayBuffer) {
            let sourceOptions: image.SourceOptions = {
              sourceDensity: 120,
              sourcePixelFormat: 0, // NV21
              sourceSize: {
                height: outputCapability.previewProfiles[0].size.height,
                width: outputCapability.previewProfiles[0].size.width
              },
            }
            try {
              let imageResource = image.createImageSource(component.byteBuffer, sourceOptions);
              imageResource.createPixelMap().then((res)=>{
                this.pixmap = res;
              });
            }catch (error) {
              let err = error as BusinessError;
              console.error('Failed to addOutput(photoOutput). errorCode = ' + err.code);
            }
          }
        } else {
          console.error('byteBuffer is null');
          return;
        }
      })
      imageObj.release();
    })

    // 4、创建相机会话,在会话中添加摄像头输入流和预览输出流,然后启动会话,预览画面就会在XComponent组件上送显。
    let captureSession = cameraManager.createSession(camera.SceneMode.NORMAL_PHOTO);
    captureSession.beginConfig();
    captureSession.addInput(cameraInput);
    captureSession.addOutput(this.previewOutput);
    captureSession.addOutput(this.photoOutput);
    captureSession.commitConfig()
    captureSession.start();
  }
  build() {
    Row() {
      Column({ space: 20 }) {
        XComponent({ id: 'xComponentId1', type: 'surface', controller: this.xComponentController })
          .onLoad(() => {
            // 在调用前确保已经获得相机权限
            abilityAccessCtrl.createAtManager().requestPermissionsFromUser(getContext(this), ['ohos.permission.CAMERA']).then(() => {
              this.getCameraImage();
            })
          })
          .height(300)
        Image(this.pixmap).height(200).width(200)
        Button('拍照')
          .onClick(() => {
            promptAction.showToast({
              message:'生成图片中,请稍等',
              duration:2500
            })
            let settings: camera.PhotoCaptureSetting = {
              quality: camera.QualityLevel.QUALITY_LEVEL_HIGH, // 设置图片质量高
              rotation: camera.ImageRotation.ROTATION_0, // 设置图片旋转角度0
              mirror: false // 设置镜像使能开关(默认关)
            };
            this.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.');
            });
          })
        Button('保存到沙箱')
          .onClick(() => {
            const context = getContext(this);
            let filePath = context.tempDir + "/test.jpg";
            console.info("path is " + filePath);
            let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
            fs.write(file.fd, this.buffer, (err, writeLen) => {
              if (err) {
                console.info("write failed with error message: " + err.message + ", error code: " + err.code);
              } else {
                promptAction.showToast({
                  message:"保存成功"
                })
                console.info("write data to file succeed and size is:" + writeLen);
                fs.closeSync(file);
              }
            });
          })
      }
      .width('100%')
    }
    .height('100%')
  }
}
分享
微博
QQ
微信
回复
1天前
相关问题
HarmonyOS 保存图片系统相册
212浏览 • 1回复 待解决
如何保存本地图片相册
1349浏览 • 1回复 待解决
HarmonyOS保存图片系统相册问题咨询
900浏览 • 1回复 待解决
如何保存一张PNG图片相册
2119浏览 • 1回复 待解决
应用沙箱图片保存到图库
1425浏览 • 1回复 待解决
HarmonyOS 图片保存相册
14浏览 • 1回复 待解决
Web组件Cookie信息保存在哪里?
707浏览 • 1回复 待解决
HarmonyOS图片保存相册问题
707浏览 • 1回复 待解决
HarmonyOS 保存图片相册问题
511浏览 • 1回复 待解决
HarmonyOS 保存图片到本地相册
191浏览 • 1回复 待解决
HarmonyOS 截图保存图片相册
189浏览 • 1回复 待解决