Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
512 views
in Technique[技术] by (71.8m points)

javascript - Saving and loading an image from localStorage

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

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

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

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" />

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...