在我的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..
如果我在URI函数中执行imgRef.put(uri);
,则图像上传有效。但我需要在该功能之外执行此操作。
如何在imageURI变量中获取结果并在以后重用?
好吧,我用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;
}
它返回要上传到服务器的文件。