Jon
Jon

Reputation: 976

How to append images into local storage?

I am trying to append images into local storage.

I have a div that I would like to hold all these images. Something as simple as:

<div id="imageContainer">
<!--have images go here-->
</div>

What I am trying to accomplish is something like this:

if (Math.floor((Math.random()*3)+1) == 1) { // 1/3 chance of conditional being true
  // append some image to #imageContainer and have it locally stored
} else {
  alert('no luck this time...');
}

So, each time that above condition is true, how would I append an image into #imageContainer and have it locally saved?

Upvotes: 1

Views: 280

Answers (2)

King Friday
King Friday

Reputation: 26076

Just in case you were not taking about images and really just meant HTML as the above folks really answered localStorage and dataURL nicely, you would do something like this...

localStorage['imageContainerHTML'] = document.getElementById('imageContainer').innerHTML;

This is only storing the HTML, not the images. For images, use the advice from the other blokes.

Upvotes: 0

vcsjones
vcsjones

Reputation: 141638

If the images are small, you could store the image in localStorage as base64 encoded data URI. For example, here is the StackOverflow image as a data URI:

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABSElEQVR42mP8DwQMeMDfrx8Z7uc6gWn59g0MHEo6KPKMhAwAgZezaxg+7FnBwMzNDzaEVVyWNANA4Fl/LsPnE9vBLpCpWQg2DKcBPx4cZPjz4QEDj0E8ileetMQz/Lh3hYHXwpNBqnAybgNeLg8EG8IioMAg6FjPwKXhDxb//fIxw8PKALBhAi4RDOKpLdgNANn+fn8jw7cbG8F8ZINghoCA4uR9+MPg348PDB+PTwQbBDIUZJCwZz9QQhgsDwoPDAMu7FzIwM7Fy8AnIsMgIq8BZPOBNf96cRFsGBMHP4N45HrcsTAr3QTDJUrGLkDDNBmEuL4xiMlqMXAo2OM2AOSCNw+vM/z89onh6fVTGIalzTyDmZDS09PBnJkzZ2JoABn05uENhk9vngDZnxkM3OMZkNVjGABj4wLIamhjADEApwGkAqoYAABh69q0dfMNBwAAAABJRU5ErkJggg==

So you would show that in an image like this:

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAA...[snip]" />

All you would have to do is create an <img> and set the src attribute to the data URI.

Upvotes: 3

Related Questions