HarmonyOS 关于照片的压缩咨询?

是否有提供压缩照片至指定大小的api?目前相机照片尺寸比较大,而上传至服务器有文件大小限制,需要压缩一下再上传。

阅读 436
1 个回答

压缩图片尺寸宽高大小,可以参考以下文档:https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/image-transformation-V5并参考以下demo:

async dealWithPic(targetWidth:
number, targetHeight:
number, targetPixelSize:
number)
{
  let path = getContext().filesDir + '/pic.png'
  // path为已获得的沙箱路径
  const imageSource: image.ImageSource = image.createImageSource(path);
  let decodingOptions: image.DecodingOptions = {
    editable: true
  }
  //创建pixelMap
  this.pixelMap = await imageSource.createPixelMap(decodingOptions);
  console.log(this.pixelMap.getPixelBytesNumber());
  //指定压缩宽、高、大小
  // this.packingDetail(500, 500, 100)

  if (this.pixelMap) {
    console.info("before scaling pixelmap." + this.pixelMap.getPixelBytesNumber());
    let imageInfo = await this.pixelMap.getImageInfo();
    let a = this.pixelMap
    //计算压缩比
    let scaleX: number = targetWidth / imageInfo.size.width;
    let scaleY: number = targetHeight / imageInfo.size.height;
    this.pixelMap.scale(scaleX, scaleY, (err: BusinessError) => {
      if (err) {
        console.error("Failed to scale pixelmap.");
        return;
      } else {
        console.log("in scaling pixelmap." + a.getPixelBytesNumber());
      }
    });
  }
  let imagePackerApi = image.createImagePacker();
  let packOpts: image.PackingOption = { format: "image/jpeg", quality: 100 };
  imagePackerApi.packing(this.pixelMap, packOpts).then((data: ArrayBuffer) => {
    console.info("in 100 quality data" + data.byteLength)
    this.compressPictures(data, targetPixelSize, 99);
  });
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
logo
HarmonyOS
子站问答
访问
宣传栏