如何从类型化数组中的二进制数据创建PNG blob? [英] How can I create a PNG blob from binary data in a typed array?

查看:410
本文介绍了如何从类型化数组中的二进制数据创建PNG blob?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些恰好是PNG的二进制数据。我想将它变成blob,获取blob的URL并将其显示为图像(或者图像URL的任何其他位置都有效,如css等。)

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

这是我尝试过的。首先,我制作了一个带有黄色F图像的小型8x8红色方块,并使用pngcrush使其变小;

Here's what I tried. First I made a small 8x8 red square with yellow "F" image and used pngcrush to make it smaller

你可以看到原始的91字节图像显示得很好(它只是8x8像素)

You can see the original 91 byte image displays just fine (it's only 8x8 pixels)

然后,对于这个示例,我将其转换为JavaScript数组,我将其复制到Uint8Array中,我从中创建了一个blob,并从blob中创建了一个URL,将其分配给图像但图像不显示。

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

如何将其显示为blob网址?

How can I get it to display as a blob url?

推荐答案

问题是 Blob 构造函数的第一个参数是放入blob中的对象数组,以便从

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, ...

var blob = new Blob([data], ...

修复它

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

这篇关于如何从类型化数组中的二进制数据创建PNG blob?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆