Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store images in Javascript object

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?

like image 478
user288134 Avatar asked Mar 07 '10 09:03

user288134


People also ask

How to store image in JavaScript?

Actually, you can create image elements using vanilla JavaScript and instantiate them prior to adding them to the document: var img1 = document. createElement("img"); img1.

How do I store an image in an object?

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. Show activity on this post. var img = new Image(); img.

How to add image in object JS?

Create Image Element in JavaScriptCreate an image element using the createElement() method on the document object. Then, set an image URL to its src attribute. Finally, add the image element to the DOM hierarchy by appending it to the body element.

What is image () in JavaScript?

Image() The Image() constructor creates a new HTMLImageElement instance. It is functionally equivalent to document. createElement('img') .


2 Answers

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

like image 78
Justin Johnson Avatar answered Sep 23 '22 03:09

Justin Johnson


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.

like image 42
Luca Matteis Avatar answered Sep 24 '22 03:09

Luca Matteis