ReactJS:上传前调整图像大小

new*_*per 2 image-resizing reactjs

在我的 reactJs 项目中,我需要在上传之前调整图像大小。

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

我试过这个,但它显示我空白的结果。我究竟做错了什么?

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.. 
Run Code Online (Sandbox Code Playgroud)

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

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

小智 13

首先,包装这个缩放器:

const resizeFile = (file) => new Promise(resolve => {
    Resizer.imageFileResizer(file, 300, 300, 'JPEG', 100, 0,
    uri => {
      resolve(uri);
    }, 'base64' );
});
Run Code Online (Sandbox Code Playgroud)

然后在异步函数中使用它:

const onChange = async (event) => {
  const file = event.target.files[0];
  const image = await resizeFile(file);
  console.log(image);
}     
Run Code Online (Sandbox Code Playgroud)


new*_*per 5

好的,我使用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;
  }
Run Code Online (Sandbox Code Playgroud)

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