if you're looking to create a blob like image for use on your website, you can easily do that by masking an image over a blog using Photoshop. First, use the blob maker app to generate a random blob. The color doesn't matter, but ensure that you have the complexity and contrast set to be exactly how you want it.
A Blob is an opaque reference to, or handle for, a chunk of data. The name comes from SQL databases, where it means “Binary Large Object.” In JavaScript, Blobs often represent binary data, and they can be large, but neither is required: a Blob could also represent the contents of a small text file.
If you must convert a file object to a blob object, you can create a new Blob object using the array buffer of the file. See the example below. const file = new File(['hello', ' ', 'world'], 'hello_world. txt', {type: 'text/plain'}); //or const file = document.
You can convert your string into a Uint8Array to get the raw data. Then create a Blob for that data and pass to URL. createObjectURL(blob) to convert the Blob into a URL that you pass to img. src.
You can do this in two ways:
XMLHttpRequest()
or fetch()
instead of an image elementFor method one and since you're already using promises, you can do:
function loadXHR(url) {
return new Promise(function(resolve, reject) {
try {
var xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.responseType = "blob";
xhr.onerror = function() {reject("Network error.")};
xhr.onload = function() {
if (xhr.status === 200) {resolve(xhr.response)}
else {reject("Loading error:" + xhr.statusText)}
};
xhr.send();
}
catch(err) {reject(err.message)}
});
}
Then get the image as Blob using it like this:
loadXHR("url-to-image").then(function(blob) {
// here the image is a blob
});
or use fetch()
in browsers which support this:
fetch("url-to-image")
.then(function(response) {
return response.blob()
})
.then(function(blob) {
// here the image is a blob
});
The other method will require a canvas:
var img = new Image;
var c = document.createElement("canvas");
var ctx = c.getContext("2d");
img.onload = function() {
c.width = this.naturalWidth; // update canvas size to match image
c.height = this.naturalHeight;
ctx.drawImage(this, 0, 0); // draw in image
c.toBlob(function(blob) { // get content as JPEG blob
// here the image is a blob
}, "image/jpeg", 0.75);
};
img.crossOrigin = ""; // if from different origin
img.src = "url-to-image";
You can try this node module
https://www.npmjs.com/package/image-to-blob
or you can convert image to canvas, then convert to blob uri:
https://github.com/blueimp/JavaScript-Canvas-to-Blob
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With