First of all JS is not my usual language, sorry if the question is not very clear.
I have been testing a code to compress the images that users upload to an <input>
the JS code of compression is working perfectly but I don't know how to do to replace the file that they have chosen in the "input" by the one that I have just generated compressed.
I want to do this because the <input>
is inside a form so I can upload the image to the server compressed.
Here is the JS fot compression:
const MAX_WIDTH = 300;
const MAX_HEIGHT = 200;
const MIME_TYPE = "image/jpeg";
const QUALITY = 0.8;
const input = document.getElementById("img-1");
input.onchange = function (ev) {
const file = ev.target.files[0]; // get the file
const blobURL = URL.createObjectURL(file);
const img = new Image();
img.src = blobURL;
img.onerror = function () {
URL.revokeObjectURL(this.src);
// Handle the failure properly
console.log("Cannot load image");
};
img.onload = function () {
URL.revokeObjectURL(this.src);
const [newWidth, newHeight] = calculateSize(img, MAX_WIDTH, MAX_HEIGHT);
const canvas = document.createElement("canvas");
canvas.width = newWidth;
canvas.height = newHeight;
const ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, newWidth, newHeight);
canvas.toBlob(
blob => {
// Do something with img in my case show in Frontend
displayInfo('Original file', file);
displayInfo('Compressed file', blob);
},
MIME_TYPE,
QUALITY);
// Only for testing and see results
document.getElementById("pruebas-tam").append(canvas);
};
};