保存并从localStorage加载图像 [英] Saving and loading an image from localStorage

查看:98
本文介绍了保存并从localStorage加载图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,我正在尝试将图像保存到 localStorage 中,然后在下一页上加载相同的图像。

So basically, I am trying to save an image into localStorage, and then load that same image on the next page.

我遇到了这个很好的例子: http://jsfiddle.net/8V9w6/

I came across this great example: http://jsfiddle.net/8V9w6/

虽然,我完全不知道这是如何工作的,因为我只使用localStorage作为极小字符串。

Although, I have absolutely no idea how this works since I have only ever used localStorage for extremely small strings.

我有一个图像通过jQuery处理的文件上传来改变

I have an image that gets changed via a file upload handled by jQuery

<img id="bannerImg" src="images/image-placeholder.jpg" alt="Banner Image" style="display:none;" width="100%" height="200px" />

我在上面添加的 jsfiddle 链接允许多个文件上传,这绝对是我不想要的。

The jsfiddle link I added above allows multiple file upload, and that is definitely something I would not like to have.

我需要知道的是我应该在第一页上放置什么来保存图像,我应该在第二页上加载图像?

What I need to know is what should I be placing on the first page to save the image, and what should I be placing on the second page to load the image?

我有保存按钮处理所有事情。

I have a save button that will be processing everything.

推荐答案

这样的事情?

var img = new Image();
img.src = 'mypicture.png';
img.load = function() {
 var canvas = document.createElement('canvas');
 document.body.appendChild(canvas);
 var context = canvas.getContext('2d');
 context.drawImage(img, 0, 0);
 var data = context.getImageData(x, y, img.width, img.height).data;
 localStorage.setItem('image', data); // save image data
};

获取第二页上的localStorage;尝试这样的事情:

Get the localStorage on the second page; try something like this:

window.onload = function() {
 var picture = localStorage.getItem('image');
 var image = document.createElement('img');
 image.src = picture;
 document.body.appendChild(image);
};

这篇关于保存并从localStorage加载图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆