How to save an image to localStorage and display it on the next page?
To whoever also needs this problem solved:
Firstly, I grab my image with getElementByID
, and save the image as a Base64. Then I save the Base64 string as my localStorage
value.
bannerImage = document.getElementById('bannerImg');
imgData = getBase64Image(bannerImage);
localStorage.setItem("imgData", imgData);
Here is the function that converts the image to a 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,/, "");
}
Then, on my next page I created an image with a blank src
like so:
<img src="" id="tableBanner" />
And straight when the page loads, I use these next three lines to get the Base64 string from localStorage
, and apply it to the image with the blank src
I created:
var dataImage = localStorage.getItem('imgData');
bannerImg = document.getElementById('tableBanner');
bannerImg.src = "data:image/png;base64," + dataImage;
Tested it in quite a few different browsers and versions, and it seems to work quite well.
Saving and loading an image from localStorage
Something like this ?
var img = new Image();
img.src = 'mypicture.png';
img.load = function() {
var canvas = document.createElement('canvas');
document.body.appendChild(canvas);
var context = canvas.getContext('2d');
context.drawImage(img, 0, 0);
var data = context.getImageData(x, y, img.width, img.height).data;
localStorage.setItem('image', data); // save image data
};
Get the localStorage on the second page; try something like this:
window.onload = function() {
var picture = localStorage.getItem('image');
var image = document.createElement('img');
image.src = picture;
document.body.appendChild(image);
};
How can I save image to local storage?
In order to recall previous "state" (blue
or green
) you'll need to get the data stored in localStorage
after the page loads:
const getData = key => JSON.parse(localStorage.getItem(key) || null);
...
document.body.onload = init;
...
function init(e) {
// Get the saved theme from LS
let data = getData('theme');
...
Keep a simple object that stores the urls of each logo (no need to save urls in LS since they themselves never change).
const logo = {
green: 'https://transpo.uconn.edu/wp-content/uploads/sites/1593/2018/10/Green-Logo-REV-DAA-jpeg-1.jpg',
blue: 'https://res.cloudinary.com/crunchbase-production/image/upload/c_lpad,h_170,w_170,f_auto,b_white,q_auto:eco,dpr_1/v1483631401/vizink60c2lcy1v9xk2s.png'
};
...
document.images[0].src = logo[data];
document.images
is a HTMLCollection -- document.images[0]
is the first <img>
on the page. If the logo isn't the first <img>
and for some reason you don't know it's index position (like if it's dynamically added), just use a more common method like good ol' .querySelector()
.
Further details are commented in example below
Note: SO does not allow the use of localStorage
so this snippet will not function as expected. For a functioning example go to:
Plunker
// This stores the urls for the logo
const logo = {
green: 'https://transpo.uconn.edu/wp-content/uploads/sites/1593/2018/10/Green-Logo-REV-DAA-jpeg-1.jpg',
blue: 'https://res.cloudinary.com/crunchbase-production/image/upload/c_lpad,h_170,w_170,f_auto,b_white,q_auto:eco,dpr_1/v1483631401/vizink60c2lcy1v9xk2s.png'
};
/*
Reference <html> and <button>
*/
const root = document.documentElement;
const btn = document.querySelector('.switch');
/*
Define functions that get and set localStorage
*/
const getData = key => JSON.parse(localStorage.getItem(key) || null);
const setData = (key, data) => localStorage.setItem(key, JSON.stringify(data));
/*
Register the <body> to the 'load' event.
When 'load' event is triggered, init(e)
is invoked
*/
document.body.onload = init;
/*
Register the <button> to the "click" event.
theme(e) event handler will be invoked.
*/
btn.addEventListener('click', theme);
// Event handler passes the Event Object
function init(e) {
// Get the saved theme from LS
let data = getData('theme');
// If there's nothing saved yet quit
if (data === null) return;
// Assign data to .value of <button>
btn.value = data;
// Remove <html> class
root.className = '';
/*
Add current theme name to <html> as a
class
*/
root.classList.add(data);
/*
Change <img> src to the property of
the logo object that matches current
theme.
*/
document.images[0].src = logo[data];
};
// Event handler passes Event Object
function theme(e) {
// declare status
let status;
// On <html> toggle both theme classes
root.classList.toggle('green');
root.classList.toggle('blue');
/*
If <html> becomes '.blue' assign 'blue'
to status, otherwise assign 'green'
*/
if (root.classList.contains('blue')) {
status = 'blue';
} else status = 'green';
// Assign status to .value of <button>
this.value = status;
/*
Change <img> src to the property of
the logo object that matches current
theme.
*/
document.images[0].src = logo[status];
// Save theme name to LS
setData('theme', status);
};
html {
font: 2ch/1.25 'Segoe UI';
}
header {
display: flex;
justify-content: space-between;
align-items: center;
}
figure {
width: 3rem;
}
img {
display: inline-block;
width: 3rem;
object-fit: contain;
}
button {
display: inline-block;
font: inherit;
width: 4rem;
padding: 2px 4px;
border-radius: 4px;
cursor: pointer;
}
button::before {
content: attr(value);
text-transform: capitalize;
}
.blue body {
background: lightsteelblue;
color: midnightblue;
}
.green body {
background: mediumseagreen;
color: forestgreen;
}
.blue button {
background: powderblue;
color: royalblue;
border-color: indigo;
}
.green button {
background: palegreen;
color: teal;
border-color: olivedrab;
}
<!doctype html>
<html class='blue'>
<head>
<link rel="stylesheet" href="lib/style.css">
</head>
<body>
<header>
<h1>Main Title</h1> <figure><img src='https://res.cloudinary.com/crunchbase-production/image/upload/c_lpad,h_170,w_170,f_auto,b_white,q_auto:eco,dpr_1/v1483631401/vizink60c2lcy1v9xk2s.png'></figure>
</header>
<button class='switch' type='button' value='blue'></button>
<script src="lib/script.js"></script>
</body>
</html>
uploading multiple images and saving them to localStorage in javascript
First, I don't think that you should use LocalStorage for this. Besides LocalStorage size is limited. In case you have a back-end, those images should be saved in the server, and then just load them with the URL, like any normal website.
In any case, I answer your question. Instead of using an array (and having that problem with the index), turn it into an object and then use the object key:
let fileList = e.target.files;
let files = {};
let index = 0;
for(let file of files) {
files[index] = file;
index ++;
}
// Now iterate object instead of array
Object.keys(files).forEach( key => {
let reader = new FileReader();
reader.addEventListener("load", () =>{
localStorage.setItem(`img${key}`,reader.result)
})
reader.readAsDataURL(files[key]);
});
Save image file in local storage and retrieve image from file path html angularjs
For storing and retrieving image from local storage you can simply use javascript. Here is an example:
bannerImage = document.getElementById('bannerImg');
imgData = getBase64Image(bannerImage);
localStorage.setItem("imgData", imgData);
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,/, "");
}
Here is the link to the StackOverflow question
Loading image from localstorage and retaining it
Convert the image to dataURI and store in localstorage. After that you can retrieve it from localstorage whenever you want to and then pass it to src of image tag to display the image. The webkit engine will take care of rendering the image from dataURI.
To save in local storage
localStorage.setItem("data", "datauriofimage")
To retrieve from localstorage
var srcImg = localStorage.getItem("data");
Save a File Image to localstorage HTML
You just lack a FileReader
to read the input file to dataURL. Jsfiddle
Html:
<input type="file" id="bannerImg" />
<img src="" id="tableBanner" />
<!-- for result output -->
<div id="res"></div>
javascript:
// Get all variables
var bannerImage = document.getElementById('bannerImg');
var result = document.getElementById('res');
var img = document.getElementById('tableBanner');
// Add a change listener to the file input to inspect the uploaded file.
bannerImage.addEventListener('change', function() {
var file = this.files[0];
// Basic type checking.
if (file.type.indexOf('image') < 0) {
res.innerHTML = 'invalid type';
return;
}
// Create a file reader
var fReader = new FileReader();
// Add complete behavior
fReader.onload = function() {
// Show the uploaded image to banner.
img.src = fReader.result;
// Save it when data complete.
// Use your function will ensure the format is png.
localStorage.setItem("imgData", getBase64Image(img));
// You can just use as its already a string.
// localStorage.setItem("imgData", fReader.result);
};
// Read the file to DataURL format.
fReader.readAsDataURL(file);
});
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,/, "");
}
function fetchimage () {
var dataImage = localStorage.getItem('imgData');
img.src = "data:image/png;base64," + dataImage;
// If you don't process the url with getBase64Image, you can just use
// img.src = dataImage;
}
// Call fetch to get image from localStorage.
// So each time you reload the page, the image in localstorage will be
// put on tableBanner
fetchimage();
Not that the jsfiddle execute this script onload
, so you may wrap them in window.onload in your own site.
Related Topics
Good Ways to Improve Jquery Selector Performance
Is There a Good JavaScript Minifier
Getting Blob Data from Xhr Request
JavaScript Parser in JavaScript
Count Number of Matches of a Regex in JavaScript
Javascript/Jquery: Test If Window Has Focus
Detect When an Image Fails to Load in JavaScript
JavaScript Sort Function. Sort by First Then by Second
How to Insert a Character After Every N Characters in JavaScript
Date VS New Date in JavaScript
Rails 4 Turbo-Link Prevents Jquery Scripts from Working
How to Prevent Default Event Handling in an Onclick Method
JavaScript to Detect If User Changes Tab
Createelement VS. Createelementns
Dynamically Using the First Frame as Poster in HTML5 Video
How to Defer Inline JavaScript
Jquery Change Event on an <Input> Element - Any Way to Retain Previous Value