问题
In my reactJs project, I need to resize image before uploading it.
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..
If I do imgRef.put(uri);
inside URI function then image upload works. but I need to do that outside of that function.
how to get result in imageURI variable and reuse it later ?
回答1:
The library which you are using will not resize the image for file upload.
It returns of new image's base64 URI or Blob. The URI can be used as the source of an component.
To resize the image: You can refer to the script here
or a working code sample demo here
回答2:
Ok I figured it out using compres.js library.
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.
来源:https://stackoverflow.com/questions/61740953/reactjs-resize-image-before-upload