Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it a good idea to store images in localStorage?

I'm making a HTML/Javascript tool that does something with images. Frankly, I just use HTML because Java or C++ GUI is way too complicated and not worth the effort.

The tool just displays an image and then displays percentual and absolute coordinates as you hover the image:

image description

My aim is to create a little GUI for "Last images" allowing to quickly display recent image. And because the application is client-only, I can't use any kind of server storage. There's a localStorage object, but to me, it seems like a bad idea to store several MB of images in it.

What do you think? Should I use localStorage for that? Or is there an alternative? Or maybe the server cooperation is totally necessary?

like image 206
Tomáš Zato - Reinstate Monica Avatar asked Sep 10 '25 14:09

Tomáš Zato - Reinstate Monica


2 Answers

You can use a compression algorithm to compress the base64 string representation of images. I used the similar approach in my code and it alowed me to store more images compared to normal case.

Compression lib: LZstring http://pieroxy.net/blog/pages/lz-string/index.html

like image 91
Vijay Avatar answered Sep 13 '25 02:09

Vijay


It's either that or using the HTML5 File API, but if you are just saving a few images under 5mb HTML5 WebStorage should be enough, like this:

If you use the web storage, and HTML5 Canvas to convert the image into text (data uri):

var img = new Image();
   img.src = "same_origin.png";

localStorage.setItem("lastImage",imgToURI(img));


function imgToURI(img){
    var canvas = document.createElement("canvas");
    var context = canvas.getContext("2d");
    canvas.width = img.width;
    canvas.height = img.height;
    context.drawImage(img,0,0);
    return canvas.toDataURL();
}

And then for retrieving the saved image:

var last = new Image();
  last.src = localStorage.getItem("lastImage1");

Note: Most browsers only allow 5mb of local storage.

Note: While localStorage is highly supported, canvas it's not supported in IE8.


Note: The HTML File API approach wouldn't be user friendly, as of now Chrome is the only one allowing writing files with their filesystem api, for the other ones you'll have to convert the images to data uri, then make a link with all the data in the form of a data uri text file, and have the user download it and reload it every time.

Hope it helps!

like image 37
undefined Avatar answered Sep 13 '25 03:09

undefined