I have a PHP script that can encode a PNG image to a Base64 string.
I\'d like to do the same thing using JavaScript. I know how to open files, but I\'m not sure how
if you need to encode HTML image object, you can write simple function like:
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");
// escape data:image prefix
return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
// or just return dataURL
// return dataURL
}
To get base64 of image by id:
function getBase64ImageById(id){
return getBase64Image(document.getElementById(id));
}
more here