Skip to content

Instantly share code, notes, and snippets.

@ogabrielguerra
Created June 23, 2019 23:06
Show Gist options
  • Save ogabrielguerra/95def799ccd44399daff21c453438fe6 to your computer and use it in GitHub Desktop.
Save ogabrielguerra/95def799ccd44399daff21c453438fe6 to your computer and use it in GitHub Desktop.
Javascript function to convert images to base64
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,/, "");
}
var base64 = getBase64Image(document.getElementById("imageid"));
/* From Stackoverflow at: https://stackoverflow.com/questions/22172604/convert-image-url-to-base64 */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment