Reputation: 1
I am trying to create a function that resize the images the user uploads. The user has the option to specify a new size.
The function works, and it does resize the images. However, the problem is that when I upload a 3MB image, the output becomes 55MB.
What did I do wrong?
Thanks in advance to anyone who helps. I'm already desperate!
const [imageBlob, setImageBlob] = useState(null);
const [isLoading, setIsLoading] = useState(false);
const [imageDimensions, setImageDimensions] = useState({
originalWidth: 0,
originalHeight: 0,
ratio: 0,
resizedWidth: 0,
resizedHeight: 0,
});
const [maintainRatio, setMaintainRatio] = useState(true);
const [resizeImageBase64, setResizeImageBase64] = useState("");
const [imageFormat, setImageFormat] = useState("png"); // Default format
const [newImageName, setNewImageName] = useState("");
const resizeImage = () => {
setIsLoading(true);
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
// Create an image element from the imageBlob (Blob -> ImageElement)
const img = new Image();
img.onload = () => {
// Set canvas width and height based on resized dimensions
canvas.width = imageDimensions.resizedWidth;
canvas.height = imageDimensions.resizedHeight;
// Draw the image onto the canvas
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
console.log(canvas.toDataURL());
const base64String =
`data:image/${imageFormat};base64,` +
canvas
.toDataURL(`image/${imageFormat}`)
.replace("data:", "")
.replace(/^.+,/, "");
setResizeImageBase64(base64String);
setIsLoading(false);
URL.revokeObjectURL(objectURL);
};
img.onerror = () => {
console.error("Failed to load image.");
};
// Create an object URL for the imageBlob and assign it to img.src
const objectURL = URL.createObjectURL(imageBlob);
img.src = objectURL;
};
Upvotes: 0
Views: 19