We get the img element with getElementById and then call getBase64Image to get the data. And then we call setItem to save the imgData to local storage. const dataImage = localStorage. getItem("imgData"); const bannerImg = document.
Saving data to localStorage in React is super easy: const [data, setData] = useState([]); useEffect(() => { localStorage. setItem('dataKey', JSON. stringify(data)); }, [data]);
Syntax to save data to localStorage: localStorage. setItem(key, value) Ex: localStorage. setItem("firstName", "Mark Zuker berg");
Thought I had this, but no. The goal: snap a photo (insurance card), save it locally, and retrieve it later.
// Get a reference to the image element
var elephant = document.getElementById("SnapIt_mobileimage_5");
var imgCanvas = document.createElement("canvas"),
imgContext = imgCanvas.getContext("2d");
// Make sure canvas is as big as the picture
imgCanvas.width = elephant.width;
imgCanvas.height = elephant.height;
// Draw image into canvas element
imgContext.drawImage(elephant, 0, 0, elephant.width, elephant.height );
console.log( 'Did that' );
// Get canvas contents as a data URL
var imgAsDataURL = imgCanvas.toDataURL("data:image/jpg;base64,");
// Save image into localStorage
try {
localStorage.setItem("elephant", imgAsDataURL);
}
catch (e) {
console.log("Storage failed: " + e);
};
//Did it work?
var pic = localStorage.getItem("elephant");
console.log( elephant );
console.log( pic );
Each step succeeds, the final output is:
<img id="SnapIt_mobileimage_5" class=" SnapIt_mobileimage_5" name="mobileimage_5" dsid="mobileimage_5" src="files/views/assets/image/IMG_0590.JPG">
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgA
On a new page, when I ask
var policy_shot = localStorage.getItem( 'elephant' );
console.log( policy_shot );
$('#TestScreen_mobileimage_1').src = policy_shot ;
It logs the binary:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUg ....
But the image doesn't appear.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With