Storing .jpg files in local storage

2019-05-01 04:42发布

I am trying to find a way to store .jpg files from my website into the localstorage to increase the site speed. Theoretical its simple: convert the picture.jpg into a base64 string and store it with setitem into the localstorage. to display the picture again just load the base64 string from the localstorage and decode back to jpg. But, as always, the practice is more difficult. Im trying to find a way to convert the .jpg files on-the-fly to base64 using html5 or javascript (no php!). Does someone had the same problem and was able to find a solution and could share the code?

4条回答
smile是对你的礼貌
2楼-- · 2019-05-01 04:52

I'm also for using HTML5 cache manifest which supports the offline case too and is designed for your problem. Don't use local storage with base64 because:

  • Base64 encoding increases the file size to 137% (!)
  • The algorithm will slow down your application, because not only the Internet Speed limits your application, also the javascript couldn't be executed as fast as on desktop computers. In my tests on moblie phones i had problems with common javascripts, so i would reduce the javascript to a minimum and your context isn't needed.
  • local storage isn't evertime supported and has also a limitation!

For Cache Manifests you can look to w3.org - Cache Manifests also on html5 Rocks there is a beginner guide.

If you do not want to use HTML5 chache manifest, you should try to increase the speed as much as possible, described in many posts here on stackoverflow, i liked the link to the presentation in the post about increasing Math Object

查看更多
叼着烟拽天下
3楼-- · 2019-05-01 04:52

It may be better/easier to use HTML5 cache by creating a cache manifest.

查看更多
叼着烟拽天下
4楼-- · 2019-05-01 04:57

You can use canvas element and toDataURL method where supported. Something like that:

var ctx = canvas.getContext("2d");

var img = new Image();

img.onload = function() {
   canvas.width = this.width;
   cavans.height = this.height;

   ctx.drawImage(this, 0, 0);

   var base64jpeg = canvas.toDataURL("image/jpeg");
}

img.src = "/images/myjpeg.jpg";

But if you want to do that to "increase the site speed", use HTML5 manifest for caching: it was designed exactly for that purpose (and offline app, of course).

查看更多
叼着烟拽天下
5楼-- · 2019-05-01 05:07

By the way, localStorage is better than browser cache. Google and Bing did some tests trying to see which caching method is faster and here are the results. SPOILER ALERT!!!! localStorage is better.

查看更多
登录 后发表回答