我试图压缩图像,但当我尝试导入图像压缩正常像这样:
import ImageCompressor from "image-compressor.js";
它给出错误:
Uncaught ReferenceError: window is not defined
这是我的代码:
const handleImage = async (e) => {
const selectedFile = e.target.files[0];
if (selectedFile) {
try {
const compressedDataURL = await compressImage(selectedFile);
console.log("Compressed dataURL: ", compressedDataURL);
setImage(compressedDataURL);
} catch (error) {
console.error("Error compressing image:", error);
}
}
};
//Compressing images function
const compressImage = async (file) => {
return new Promise((resolve, reject) => {
new ImageCompressor(file, {
quality: 0.5, // Adjust the quality as needed
success(result) {
const reader = new FileReader();
reader.onload = (e) => {
const imageData = e.target.result;
resolve(`data:image/jpeg;base64,${btoa(imageData)}`);
};
reader.readAsBinaryString(result);
},
error(e) {
reject(e);
},
});
});
};
我尝试的另一种方法是在压缩函数中导入图像压缩器:
const compressImage = async (file) => {
try {
// Import the ImageCompressor class from the library
const { ImageCompressor } = await import("image-compressor.js");
return new Promise((resolve, reject) => {
new ImageCompressor(file, {
quality: 0.5, // Adjust the quality as needed
success(result) {
const reader = new FileReader();
reader.onload = (e) => {
const imageData = e.target.result;
resolve(`data:image/jpeg;base64,${btoa(imageData)}`);
};
reader.readAsBinaryString(result);
},
error(e) {
reject(e);
},
});
});
} catch (error) {
console.error("Error importing ImageCompressor:", error);
}
};
但它只是给出了错误,它不能是一个状态变量
1条答案
按热度按时间tquggr8v1#
使用
useEffect
导入图像压缩器,如下所示: