Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

224
Vistas
Replace the image in "<input>" by a new one with the reduced size

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);
    };
};
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

After many tests I managed to find the solution, adding these lines just where we have the 'blob' we can replace the input with the new compressed image. The solution is based on creating a file using the Blob and then assigning it to a DataTransfer and finally assigning it back to the Input.

displayInfo('Original file', file);
displayInfo('Compressed file', blob);

// Here is where we convert the blob into a file and put inside DataTransfer
let newfile = new File([blob], "filename.ext",{type:MIME_TYPE, 
lastModified:new Date().getTime()});
let container = new DataTransfer();
container.items.add(newfile);
input.files = container.files;
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda