Saving and Displaying Images Using LocalStorage
Question:
How can I save an uploaded image to localStorage, then display it on a subsequent page?
Answer:
Saving the Image
- Get the image element using getElementById('bannerImage').
- Convert the image to a Base64 string using the getBase64Image() function:
function getBase64Image(img) {
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var dataURL = canvas.toDataURL("image/png");
return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}
- Save the Base64 string to localStorage using localStorage.setItem("imgData", imgData).
Displaying the Image
- On the next page, create an image element with a blank src attribute: .
- Get the Base64 string from localStorage using localStorage.getItem('imgData').
- Set the src attribute of the image to the Base64 string: bannerImg.src = "data:image/png;base64," dataImage.
The above is the detailed content of How to Save and Display Images Using LocalStorage?. For more information, please follow other related articles on the PHP Chinese website!
Statement:The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn