English 中文(简体)
将图像存储在Javascript对象中。
原标题:Store images in Javascript object

我不确定这是否可能,但我想将图像存储在JavaScript变量或对象中,当页面加载时,我希望在所需位置显示这些图像。

我想知道一些图片是否已被转换为二进制形式。它们能否使用JavaScript转换回图片?

最佳回答

似乎OP正在请求如何在JavaScript中创建数据岛,特别是针对图像。之前给出的答案没有提供这样的方法,所以我在这里提供给您。

基本上,您将图像编码为 base64 字符串,然后将其设置为 DOM 元素的源。将 Image 对象的源设置为 url 不等效,因为它需要额外的 HTTP 连接。

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

问题回答

您可以简单地使用。

var img = new Image();
img.src = "http://yourimage.jpg";

创建DOM图像。

OM图像是一个包含图像二元形式的记忆器,因此没有必要将其改成像,因为它已经 s。

你看,这是一个简单的问题。但是,解决这个问题的方法并不是你现在尝试的那种方法。

What you think will work:
We ll store the image (its binary data) in a js variable, and then slap it on the page any time.

How it will work much more easily:
you just have to create a DOM image on the page, and set its source. The browser will fetch the image from the server automatically.

例子:

页: 1

var img_src = "http://someserver/yourimage.png";
var node = document.getElementById( the-node-in-which-i-want-my-image );
node.innerHTML = "<img src= "+img_src+"  alt= my image >";

示例2:(使用jQuery)- 本质上与上面相同,只不过更容易编写:

var img_src = "http://someserver/yourimage.png";
$( #the-node-in-which-i-want-my-image )
    .html("<img src= "+img_src+"  alt= my image >");

现在还有一件事情:在此代码运行之后,浏览器开始获取图像,因此图像实际上在您将其插入到DOM中后稍微出现一点。

为了避免这种情况,您可以使用预取功能获取图片:

var prefetch = new Image();
prefetch.src = "http://someserver/yourimage.png";

干杯!





相关问题
CSS working only in Firefox

I am trying to create a search text-field like on the Apple website. The HTML looks like this: <div class="frm-search"> <div> <input class="btn" type="image" src="http://www....

image changed but appears the same in browser

I m writing a php script to crop an image. The script overwrites the old image with the new one, but when I reload the page (which is supposed to pickup the new image) I still see the old one. ...

Firefox background image horizontal centering oddity

I am building some basic HTML code for a CMS. One of the page-related options in the CMS is "background image" and "stretch page width / height to background image width / height." so that with large ...

Separator line in ASP.NET

I d like to add a simple separator line in an aspx web form. Does anyone know how? It sounds easy enough, but still I can t manage to find how to do it.. 10x!

热门标签