Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get image data from (blob) from the img tag (opposite method to URL.createObjectURL)

Inside my HTML code I have following IMG tag:

<img src="picture.png"  id="picture" />

I would like to create in image Blob object (https://developer.mozilla.org/en-US/docs/Web/API/Blob) (to use it further in FirefoxOS web activity) having it's uri ("picture.png"). I guess I need the method which works in opposite way to URL.createObjectURL:

https://developer.mozilla.org/en-US/docs/Web/API/URL.createObjectURL

like image 609
bluszcz Avatar asked Mar 19 '23 21:03

bluszcz


2 Answers

The Fetch API is now suitable, as used in the docs:

Using_Fetch#Checking_that_the_fetch_was_successful

https://developer.mozilla.org/en-US/docs/Web/API/Body/blob

Simply:

fetch("picture.png")
.then(res => res.blob())
.then(blob => {
    // use blob...
});
like image 132
Lyall Avatar answered Apr 06 '23 14:04

Lyall


If you don't need a byte-by-byte copy of the image (e.g. if you don't mind that jpg is converted to png), then you can draw the image on a <canvas>, and use .toBlob() to get a blob for it.

If you need the original data as a blob, or if the image is hosted at a different origin, then you can use the code at https://stackoverflow.com/a/21136980 (for same-origin requests, just use x.open('GET', 'picture.png');).

like image 28
Rob W Avatar answered Apr 06 '23 15:04

Rob W