以Javascript对象存储图像 [英] Store images in Javascript object
问题描述
我不确定这是否可行,但我想将图像存储在JavaScript变量或对象中,并且当页面加载时,我想让这些图像出现在所需的位置。
I am not sure if this is possible, but I want to store an image in a JavaScript variable or an object and when the page loads, I want to make those images appear where desired.
我想知道一些图像是否转换为二进制形式。它们可以用JavaScript转换回图像吗?
I want to know if some images are converted to binary form. Can they be converted back to images with JavaScript?
推荐答案
看来OP正在请求如何在JavaScript中做数据孤岛,专门用于图像。以前的答案都没有提供这样的方法,所以在这里你去。
It appears that the OP is requesting how to do data islands in JavaScript, specifically for images. None of the answers previously given provide such a method, so here you go.
基本上,您将图像编码为base64字符串,然后将其设置为DOM元素。将 Image
对象的源设置为url并不等同,因为它需要添加HTTP连接。
Basically, you encode the image as a base64 string and then set that as the source of a DOM element. Setting the source of an Image
object to a url is not equivalent, since it requires an addition HTTP connection.
var data = 'data:image/gif;base64,'+
'R0lGODlhAAEwAMQAAJ2M5Me98GRK1DoYyYBr3PHv++Pe99XO81Y50auc6PBkZEgpzbmt7HJa2I57'+
// snip //
'fS3CqU7XGYgE+GqHvrLJ8Tr6qXmqiwAF9CffgnMNqmWHAWNBwwGsKpKsrmJqltOOV69nuYxSkqpo'+
'Tata18rWtrr1rTIIAQA7';
var icon_elem = document.getElementById("icon_here");
icon_elem.src = data;
上面的代码和一个完整的例子可以在这里找到: http://www.kawa.net/works/js/data-scheme/base64-e.html
The above code and a full example can be found here: http://www.kawa.net/works/js/data-scheme/base64-e.html
这篇关于以Javascript对象存储图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!