bluszcz
bluszcz

Reputation: 4128

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

Upvotes: 6

Views: 19004

Answers (2)

Lyall
Lyall

Reputation: 151

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...
});

Upvotes: 7

Rob W
Rob W

Reputation: 348992

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');).

Upvotes: 1

Related Questions