HarmonyOS 上传身份证照片,分为拍照和选择相册两种方式,现在需要将上传的图片压缩至500KB以下,并存储在沙箱中,麻烦给个完整的demo,实现这两种方式的上传。

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

关于图片压缩可以参考:https://gitee.com/harmonyos-cases/cases/tree/master/CommonAppDevelopment/feature/imagecompression

选择相册图片并将其保存至应用沙箱目录可以参考:

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';
import photoAccessHelper from '@ohos.file.photoAccessHelper';

let context = 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;
console.log('保存路径为'+pathDir)
let filePath = pathDir + '/picture.jpg'
fs.createRandomAccessFileSync(filePath, fs.OpenMode.CREATE);
let uri = fileuri.getUriFromPath(filePath);
async function photo() {
  try {
    let pickerProfile = new CameraPosition(camera.CameraPosition.CAMERA_POSITION_BACK, uri)
    let pickerResult: picker.PickerResult = await picker.pick(context,
      [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}`);
  }
}
async function picture() {
  let PhotoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
  PhotoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
  PhotoSelectOptions.maxSelectNumber = 1;
  let photoPicker = new photoAccessHelper.PhotoViewPicker();
  photoPicker.select(PhotoSelectOptions).then((PhotoSelectResult: photoAccessHelper.PhotoSelectResult) => {
    let photouri: Array<string> = PhotoSelectResult.photoUris
    let file = fs.openSync(photouri[0], fs.OpenMode.READ_ONLY)
    let file2 = fs.openSync(pathDir+'/picture2.jpg', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE)
    fs.copyFileSync(file.fd, file2.fd)
    fs.closeSync(file);
    fs.closeSync(file2);
  })
}

@Entry
@Component
export struct Index {
  build() {
    Column() {
      Button('选择并保存').onClick(() => {
        picture()
      })
      Button('拍照并保存').onClick(() => {
        photo()
      })
    }
  }
}
分享
微博
QQ
微信
回复
1天前
相关问题
HarmonyOS 相册/拍照 压缩 上传demo
84浏览 • 1回复 待解决
js获取canvas对象两种方式有啥不同?
7603浏览 • 1回复 待解决
HarmonyOS 两种模式布局如何兼容。
530浏览 • 1回复 待解决
PolarDB 集群连接地址包括哪两种
2878浏览 • 1回复 待解决