I am using Cordova's camera plugin to get a Picture (getPicture() method). It returns the picture taken in blob url format. I am saving the blob url of the image in a key of an object that I am saving in the LocalStorage. However, the problem is that when I retrieve the blob url from local storage and set the image's src on another page, the image is not displayed. It is displayed as shown in the image below.
I read somewhere that this is because blob urls are only valid for the page they were generated on. Is there a way I can make the generated image usable on another page?
What I do is, convert image in Base64 string and then store that Base64 string to localstorage.
For Ex
Get image by id and store image to localstorage
image = document.getElementById('myImage');
imgData = getBase64Image(image);
localStorage.setItem("imgData", imgData);
Base64 Conversion
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 any next page or same page you can retrieve Base64 image from localstorage and display to page
var dataImage = localStorage.getItem('imgData');
imageTag = document.getElementById('myImage');
imageTag.src = "data:image/png;base64," + dataImage;