Image URL to Blob in JavaScript
Last updated: January 20, 2023.
If you have file or file-like data loaded in JavaScript, you can create a new Blob out of it by using the Blob()
constructor.
But sometimes, as if often the case with images, your data source is a URL.
For this, you can use the Fetch API to get the image data and process it into a Blob.
To do so, call the blob()
method on the response object, which triggers the payload to read to a Blob:
fetch('https://picsum.photos/300/300')
.then(res => res.blob())
.then(blob => console.log(blob))
// Blob {size: 9469, type: 'image/jpeg'}
As you can see, this code alone does all of the hard work of constructing a Blob object from the image.
Now you have all of the Blob methods available to you that can be useful when processing the image data.
For example, you can create a local URL to the Blob image and use it to start a download of the image in the user’s browser:
fetch('https://picsum.photos/300/300')
.then(res => res.blob())
.then(blob => handler(blob))
function handler(inputBlob) {
const url = URL.createObjectURL(inputBlob);
// Creates URL to the image Blob in memory
const a = document.createElement('a');
a.setAttribute('href', url);
a.setAttribute('download', 'fetched-image.jpeg');
// Create a download link in HTML
a.style.display = 'none';
document.body.appendChild(a);
a.click(); // Simulates click
document.body.removeChild(a);
URL.revokeObjectURL(url);
// Removes download link and image URL and image from memory
}
You can also now use the FileReader to read the Blob and and output its contents in string format so that it can be saved in localStorage or passed to a server or another page as a URL parameter.
URL to File object
A File object is the same as a Blob object but contains additional metadata about the file contents, such as filename and a timestamp for when the File object was created.
Below is a reusable function for doing that, which uses data from blob
to create it:
async function URLtoFile(url) {
const res = await fetch(url);
const blob = await res.blob();
// Gets URL data and read to blob
console.log(blob);
const mime = blob.type;
const ext = mime.slice(mime.lastIndexOf("/") + 1, mime.length);
// Gets blob MIME type (e.g. image/png) and extracts extension
const file = new File([blob], `filename.${ext}`, {
type: mime,
})
// Creates new File object using blob data, extension and MIME type
console.log(file);
}
URLtoFile('https://picsum.photos/300/300');
// File {
// name: filename.jpeg,
// lastModified: 1674215820866,
// webkitRelativePath: "",
// size: 8912,
// type: "image/jpeg"
// }
URLtoFile('https://httpbin.org/get');
// File {
// name: "filename.json",
// lastModified: 1674217178035,
// webkitRelativePath: "",
// size: 560,
// type: "application/json"
// }
Related links
- OpenJavaScript: