Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store and retrieve image to localStorage?

Tags:

People also ask

How do I store images in local storage?

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.

How do I store images in local storage in react?

Saving data to localStorage in React is super easy: const [data, setData] = useState([]); useEffect(() => { localStorage. setItem('dataKey', JSON. stringify(data)); }, [data]);

How do I save a file in local storage?

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.

  1. Is there a simpler approach?
  2. Why is the getItem (binary) preceded by data:image/png; instead of data:image/jpg ?
  3. Is that why it doesn't display, or am I doing something else wrong?