Home > Article > Web Front-end > 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:
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:
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!