Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

873
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!