16

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)

91 byte png

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?

1 Answer 1

31

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

Sign up to request clarification or add additional context in comments.

1 Comment

Holy crap I can't believe all I needed was [ ] around data.... Mark this the answer and reap the internet points.