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

877
Visualizações
Convert image to Blob, javascript, react

I feel that I have a pretty straight forward problem, but I've been taring my hair finding a question that answers it:

I have a create-react-app application.

I have an image in src/images/image.png, and I want to, programatically, convert that image to a Blob.

How?

If I render

<img src={require(relativePathToImage)} />

I see the image.

And if I get it through an input field like:

<input
  type="file"
  accept="image/png"
  onChange={(e) => setImage(e.target.files[0])}
/>

I get the correct Blob set to image.

But how do I bypass doing it manually through the input-field and go directly from
relativePathToImage to Blob?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can use javascript:

function imgToBlob(url) {
 let img=new Image();
 img.src=url;
 let canvas=document.createElement('canvas');
 img.onload=function() {
  canvas.width=img.width;
  canvas.height=img.height;
  canvas.getContext('2d').drawImage(img,0,0);
  canvas.toBlob(setLink,'image/png',1) // about toBlob function: https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob
   }
  }

function setLink(blob) {
 document.querySelector('a').href=URL.createObjectURL(blob)
  }

For this html:

<a>Blob link</a>

Edit: You shuld add to the imgToBlob function line img.crossOringin="anonymus"

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