This should be simple enough, but after wrestling with it for hours, I still can\'t get it to work. So far, all my attempts have resulted in the image becoming \'corrupted or tr
You can get the data uri (which will contain the base 64 encoding) via JavaScript using the HTML5 canvas element.
// I'm assuming here you've put the image in an tag on the page already.
// If not, you'll need to adapt this a bit, or perhaps this approach is just
// not right for your situation.
var image = document.getElementById('id-of-image-you-want');
var canvas = w.document.createElement("canvas");
canvas.width = image.width;
canvas.height = image.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(image, 0, 0);
try {
var dataUri = canvas.toDataURL();
} catch (e) {
console.log("D'oh!"); // Improve this error handling, obviously.
}
dataUri
will now contain the data uri for the image which will contain, along with a short prefix, the base 64 encoding of the image.
Be sure to add detection for canvas support. IE 8 and older do not support it.