HarmonyOS鸿蒙Next中上传图片的时候如何对图片大小进行压缩

HarmonyOS鸿蒙Next中上传图片对图片进行压缩可以先获取图片的PixelMap对象,然后使用PixelMap对图片进行处理,处理后把图片保存到缓存目录执行上传

https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/image-encoding-V5

convertFileUri = (uri: string) => {
    //uri  file://media/Photo/296/IMG_1729581568_269/IMG_20241022_151748.jpg
    fs.open(uri, fs.OpenMode.READ_ONLY).then(async (data) => {

      let context = getContext(this) as Context
      //获取时间戳
      let fileName = Date.now()
      //获取文件后缀名
      let extname = uri.split(".")[1]
      //cacheDir对应的文件路径
      let newDir = context.cacheDir + "/" + fileName + "." + extname
      //对图片进行压缩
      // 1、获取图片对应的PixelMap
      let pixelMap = await this.getPixelMap(data.fd)
      //2、对图片进行压缩
      pixelMap?.scale(0.2,0.2).then(()=>{
         //3、把pixelMap资源保存到newDir里面  https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/image-encoding-V5
        const imagePackerApi = image.createImagePacker();
        let packOpts : image.PackingOption = { format:"image/jpeg", quality:100 };
        imagePackerApi.packing(pixelMap, packOpts).then( (data : ArrayBuffer) => {
          // data 为打包获取到的文件流,写入文件保存即可得到一张图片
          let fileData=fs.openSync(newDir, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE)
          fs.writeSync(fileData.fd,data)
          this.doUpload(newDir, extname)
        }).catch((error : BusinessError) => {
          console.error('Failed to pack the image. And the error is: ' + error);
        })
      })

    }).catch((err: Error) => {
      this.message = "fsOpen Error message=" + err.message
    })
  }
  // 获取PixelMap
  getPixelMap = async (fd: number) => {
    const imageSourceApi = image.createImageSource(fd);
    if (!imageSourceApi) {
      return;
    }
    let pixelMap = await imageSourceApi.createPixelMap({
      editable: true
    })
    return pixelMap
  }

更多关于HarmonyOS鸿蒙Next中上传图片的时候如何对图片大小进行压缩的实战教程也可以访问 https://www.itying.com/category-93-b0.html

回到顶部