Home > Web Front-end > JS Tutorial > How to Save and Display Images Using LocalStorage?

How to Save and Display Images Using LocalStorage?

Susan Sarandon
Release: 2024-11-25 10:04:12
Original
1015 people have browsed it

How to Save and Display Images Using LocalStorage?

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

  1. Get the image element using getElementById('bannerImage').
  2. 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,/, "");
}
Copy after login
  1. Save the Base64 string to localStorage using localStorage.setItem("imgData", imgData).

Displaying the Image

  1. On the next page, create an image element with a blank src attribute: .
  2. Get the Base64 string from localStorage using localStorage.getItem('imgData').
  3. 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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template