Home  >  Article  >  Web Front-end  >  How Can I Save an Image to localStorage and Display it on the Next Page?

How Can I Save an Image to localStorage and Display it on the Next Page?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-25 19:53:10263browse

How Can I Save an Image to localStorage and Display it on the Next Page?

Saving an Image to localStorage and Displaying it on the Next Page

Your requirement is to upload an image, save it in localStorage, and then display it on a subsequent page. Here's a solution to address this need:

Saving the Image

Once you have displayed the image on the page using the HTML and JavaScript functions you mentioned, follow these additional steps when the 'Save' button is clicked:

  1. Retrieve the HTML element for the banner image using document.getElementById('bannerImg').
  2. Convert the image to a Base64 string using the getBase64Image function provided below.
  3. Save the Base64 string as a localStorage item with localStorage.setItem("imgData", imgData).

Function to Convert Image to Base64 String:

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,/, "");
}

Displaying the Image on the Next Page

On the subsequent page, create an image with an empty src attribute:

<img src="">

Then, execute the following lines once the page loads:

  1. Retrieve the Base64 string from localStorage using var dataImage = localStorage.getItem('imgData').
  2. Get the HTML element for the table banner image with bannerImg = document.getElementById('tableBanner').
  3. Set the image's src attribute to the Base64 string:

    bannerImg.src = "data:image/png;base64," + dataImage;

This approach allows you to save the image in localStorage and display it on the next page without any issues.

The above is the detailed content of How Can I Save an Image to localStorage and Display it on the Next Page?. 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