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.
- Is there a simpler approach?
- Why is the getItem (binary) preceded by data:image/png; instead of data:image/jpg ?
- Is that why it doesn't display, or am I doing something else wrong?