Store images in Javascript object

2019-01-13 00:15发布

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.

I want to know if some images are converted to binary form. Can they be converted back to images with JavaScript?

3条回答
Summer. ? 凉城
2楼-- · 2019-01-13 00:35

You can simply use

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

to create a DOM image.

A DOM image is an object in memory that contains the image binary form, so there's no need to convert it back to an image since it's already one.

查看更多
相关推荐>>
3楼-- · 2019-01-13 00:40

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.

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;

The above code and a full example can be found here: http://www.kawa.net/works/js/data-scheme/base64-e.html

查看更多
够拽才男人
4楼-- · 2019-01-13 00:48

See, this is a simple matter. But the method to approach this problem is not the way you are trying right now.

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.

Examples:

ex-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'>";

ex-2: (using jquery) - this is essentially the same as above, only much easier to write:

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

Now, there's one more thing: the browser starts fetching the image after this code runs, so the image actually appears a little after you insert it into the DOM.

To prevent this, you can pre-fetch the images using:

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

Cheers!

查看更多
登录 后发表回答