从Javascript变量中的数据创建HTML图像

时间:2021-08-27 08:57:34

I have image data (either JPEG or PNG) in a Javascript variable. How do I display the image in an HTML document? These are very large images and code like this doesn't work because the URI is too long:

我在Javascript变量中有图像数据(JPEG或PNG)。如何在HTML文档中显示图像?这些是非常大的图像和像这样的代码不能工作,因为URI太长:

// doesn't work because the URI is too long
$('img#target').attr('src', 'data:...');

Using canvas is probably the answer but I cannot figure out how to load it with the image data.

使用canvas可能是答案,但我不知道如何用图像数据加载它。

In case you are wondering: no, I cannot just download the image data directly to the img tag. It came from the server encrypted and was decrypted within the browser using Javascript.

如果您想知道:不,我不能直接下载图像数据到img标签。它来自服务器加密,并在浏览器中使用Javascript进行解密。

Thanks,
-- Art Z.

谢谢,Z——艺术。

2 个解决方案

#1


8  

To use a data URL to draw on a canvas:

使用数据URL在画布上绘制:

var img = new Image;
img.onload = function(){
  myCanvasContext.drawImage(img,0,0);
};
img.src = "data:...";

Per this question/answer be sure that you set the onload before the src.

根据这个问题/答案,请确保在src之前设置onload。

You say that "the URI is too long", but it is not clear what you mean by this. Only IE8 has a 32kB limit on the data URI; for other browsers it should work fine. If you are experiencing an error, please describe it.

您说“URI太长”,但是不清楚您的意思是什么。只有IE8对数据URI有32kB的限制;对于其他浏览器,它应该可以正常工作。如果你正在经历一个错误,请描述它。

#2


4  

It turns out that

事实证明,

$('img#target').attr('src', 'data:...');

does work in all except IE. My problem originated elsewhere.

除了IE,其他都可以。我的问题是其他地方。

#1


8  

To use a data URL to draw on a canvas:

使用数据URL在画布上绘制:

var img = new Image;
img.onload = function(){
  myCanvasContext.drawImage(img,0,0);
};
img.src = "data:...";

Per this question/answer be sure that you set the onload before the src.

根据这个问题/答案,请确保在src之前设置onload。

You say that "the URI is too long", but it is not clear what you mean by this. Only IE8 has a 32kB limit on the data URI; for other browsers it should work fine. If you are experiencing an error, please describe it.

您说“URI太长”,但是不清楚您的意思是什么。只有IE8对数据URI有32kB的限制;对于其他浏览器,它应该可以正常工作。如果你正在经历一个错误,请描述它。

#2


4  

It turns out that

事实证明,

$('img#target').attr('src', 'data:...');

does work in all except IE. My problem originated elsewhere.

除了IE,其他都可以。我的问题是其他地方。