'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?



Solution 1:[1]

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"

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1