I've been attempting to compress an image, but when I try to import the ImageCompressor normally like this:
import ImageCompressor from "image-compressor.js";
It throws an error:
Uncaught ReferenceError: window is not defined
This is the section of my code:
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);
}
}
};
//Function for compressing images
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);
},
});
});
};
Another approach I attempted was importing the image compressor inside the compression function:
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);
}
};
However, it resulted in an error stating that it cannot be a state variable.