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

12,945

Solution 1

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

Solution 2

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

Share:
12,945
bluszcz
Author by

bluszcz

Python / HTTP / XMPP / Linux / C / JS geek. System architect, web developer, vegan,

Updated on June 11, 2022

Comments