I have some binary data that happens to be a PNG. I'd like turn it into a blob, get a URL for the blob and display it as an image (or any places else an image URL is valid like css etc..)
Here's what I tried. First I made a small 8x8 red square with yellow "F" image and used pngcrush to make it smaller
You can see the original 91 byte image displays just fine (it's only 8x8 pixels)
Then, for this sample, I converted that to an JavaScript array, I copy it into a Uint8Array, I make a blob from that and a URL from the blob, assign that to an image but the image does not display.
var data = new Uint8Array([
137,80,78,71,13,10,26,10,0,0,0,13,73,72,68,82,0,0,0,8,0,0,
0,8,8,2,0,0,0,75,109,41,220,0,0,0,34,73,68,65,84,8,215,99,120,
173,168,135,21,49,0,241,255,15,90,104,8,33,129,83,7,97,163,136,
214,129,93,2,43,2,0,181,31,90,179,225,252,176,37,0,0,0,0,73,69,
78,68,174,66,96,130]);
var blob = new Blob(data, { type: "image/png" });
var url = URL.createObjectURL(blob);
var img = new Image();
img.src = url;
console.log("data length: " + data.length);
document.body.appendChild(img);
img { width: 100px; height: 100px; }
How can I get it to display as a blob url?
Not an answer but a question. I need to do this as well.
Question: how did you get the bytes in var data = new Uint8Array([
? And do they include the width/height somehow?
In my case, I need to just start with the raw bytes in the image. The mystery is how to include the width/height as well as the data.
The issue was the first argument to the Blob
constructor is an array of objects to put in the blob so changing it from
var blob = new Blob(data, ...
to
var blob = new Blob([data], ...
fixed it
var data = new Uint8Array([
137,80,78,71,13,10,26,10,0,0,0,13,73,72,68,82,0,0,0,8,0,0,
0,8,8,2,0,0,0,75,109,41,220,0,0,0,34,73,68,65,84,8,215,99,120,
173,168,135,21,49,0,241,255,15,90,104,8,33,129,83,7,97,163,136,
214,129,93,2,43,2,0,181,31,90,179,225,252,176,37,0,0,0,0,73,69,
78,68,174,66,96,130]);
var blob = new Blob([data], { type: "image/png" });
var url = URL.createObjectURL(blob);
var img = new Image();
img.src = url;
console.log("data length: " + data.length);
console.log("url: " + url);
document.body.appendChild(img);
img { width: 100px; height: 100px; image-rendering: pixelated; }
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