Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

223
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda