ReactJS:上传前调整图片大小 [英] ReactJS: Resize image before upload

查看:402
本文介绍了ReactJS:上传前调整图片大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的reactJs项目中,我需要在上载图像之前对其进行调整大小.

In my reactJs project, I need to resize image before uploading it.

我正在使用 react-image-file-resizer 库有一个简单的例子,但对我不起作用.

I am using react-image-file-resizer library which has a simple example but not working for me.

我已经尝试过了,但是结果显示为空白.我在做什么错了?

I have tried this but its shows me blank result. What am I doing wrong?

var imageURI = '';
const resizedImg = await Resizer.imageFileResizer(
  fileList.fileList[0].originFileObj,
  300,
  300,
  'JPEG',
  100,
  0,
  uri  => {
    imageURI = uri 
    console.log(uri )  // this show the correct result I want but outside of this function
  },
  'blob'
);
console.log(resizedImg)
console.log(imageURI)

// upload new image
...uploading image here.. 

如果我在URI函数中执行imgRef.put(uri);,则图片上传有效.但是我需要在该功能之外执行此操作.

If I do imgRef.put(uri); inside URI function then image upload works. but I need to do that outside of that function.

如何在imageURI变量中获取结果并在以后重用?

how to get result in imageURI variable and reuse it later ?

推荐答案

好,我使用 compres.js 库.

  async function resizeImageFn(file) {

    const resizedImage = await compress.compress([file], {
      size: 2, // the max size in MB, defaults to 2MB
      quality: 1, // the quality of the image, max is 1,
      maxWidth: 300, // the max width of the output image, defaults to 1920px
      maxHeight: 300, // the max height of the output image, defaults to 1920px
      resize: true // defaults to true, set false if you do not want to resize the image width and height
    })
    const img = resizedImage[0];
    const base64str = img.data
    const imgExt = img.ext
    const resizedFiile = Compress.convertBase64ToFile(base64str, imgExt)
    return resizedFiile;
  }

它返回一个要上传到服务器的文件.

it return a file to be uploaded to server.

这篇关于ReactJS:上传前调整图片大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆