jQuery 从 localStorage 保存和加载图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19158887/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Saving and loading an image from localStorage
提问by Fizzix
So basically, I am trying to save an image into localStorage
, and then load that same image on the next page.
所以基本上,我试图将图像保存到localStorage
,然后在下一页加载相同的图像。
I came across this great example: http://jsfiddle.net/8V9w6/
我遇到了这个很好的例子:http: //jsfiddle.net/8V9w6/
Although, I have absolutely no idea how this works since I have only ever used localStorage for extremely small strings.
虽然,我完全不知道这是如何工作的,因为我只将 localStorage 用于极小的字符串。
I have an image that gets changed via a file upload handled by jQuery
我有一个通过 jQuery 处理的文件上传更改的图像
<img id="bannerImg" src="images/image-placeholder.jpg" alt="Banner Image" style="display:none;" width="100%" height="200px" />
The jsfiddle
link I added above allows multiple file upload, and that is definitely something I would not like to have.
jsfiddle
我在上面添加的链接允许上传多个文件,这绝对是我不想拥有的。
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.
我有一个save
可以处理所有内容的按钮。
回答by Paul Rad
Something like this ?
像这样的东西?
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
};
Get the localStorage on the second page; try something like this:
获取第二页的localStorage;尝试这样的事情:
window.onload = function() {
var picture = localStorage.getItem('image');
var image = document.createElement('img');
image.src = picture;
document.body.appendChild(image);
};