0

How can i convert selected image into base64 and then save it in the local Storage for later use.

var image = document.getElementById("image");
    image.addEventListener('change', function() {
    //How to 
    });
Osama Xäwãñz
  • 437
  • 2
  • 8
  • 21

2 Answers2

0

Just look at this post, they explain exactly what you need : https://hacks.mozilla.org/2012/02/saving-images-and-files-in-localstorage/

But instead of base64 encoding, they extract the image data using canvas + toDataUrl() which convert the image data from Blob to Data URL.

Be careful with images loaded from external websites, the crossOrigin policy may throw a Security error. (See 22710627)

// Get a reference to the image element
var elephant = document.getElementById("elephant");

// Take action when the image has loaded
elephant.addEventListener("load", function () {
    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);

    // Get canvas contents as a data URL
    var imgAsDataURL = imgCanvas.toDataURL("image/png");

    // Save image into localStorage
    try {
        localStorage.setItem("elephant", imgAsDataURL);
    }
    catch (e) {
        console.log("Storage failed: " + e);
    }
}, false);

Hope this helps you :)

Community
  • 1
  • 1
Sir McPotato
  • 899
  • 7
  • 21
0

How to convert image into base64 string using javascript

You can use the HTML5 for it:

Create a canvas, load your image into it and then use toDataURL() to get the base64 representation (actually, it's a data: URL but it contains the base64-encoded image).

Then save this data to lcoalStorage:

localStorage.setItem('imgBase64', this.yourVariable);
Community
  • 1
  • 1
Taras Kovalenko
  • 2,323
  • 3
  • 24
  • 49