How to save an image to localStorage and display it on the next page with JavaScript?

Spread the love

Sometimes, we want to save an image to localStorage and display it on the next page with JavaScript.

In this article, we’ll look at how to save an image to localStorage and display it on the next page with JavaScript.

How to save an image to localStorage and display it on the next page with JavaScript?

To save an image to localStorage and display it on the next page with JavaScript, we save the image as a base64 URL.

Then we write

const getBase64Image = (img) => {
  const canvas = document.createElement("canvas");
  canvas.width = img.width;
  canvas.height = img.height;

  const ctx = canvas.getContext("2d");
  ctx.drawImage(img, 0, 0);

  const dataURL = canvas.toDataURL("image/png");
  return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
};

const bannerImage = document.getElementById("bannerImg");
const imgData = getBase64Image(bannerImage);
localStorage.setItem("imgData", imgData);

to select the img element with getElementById.

Then we call getBase64Image with the img element to put the image in the canvas with drawImage.

And then we get the base64 URL from toDataURL.

Next we call setItem to save the imgData to local storage.

Then we get the data in the next page with

const dataImage = localStorage.getItem("imgData");
bannerImg = document.getElementById("tableBanner");
bannerImg.src = "data:image/png;base64," + dataImage;

we call getItem to get the image URL.

Then we select the img element with getElementById.

And then we set the src property of it to the image’s base64 URL.

Conclusion

To save an image to localStorage and display it on the next page with JavaScript, we save the image as a base64 URL.

Leave a Reply

Your email address will not be published.