Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Converting a local image to base64 using JavaScript (canvas + regexp)
function imageToBase64(img)
var canvas, ctx, dataURL, base64;
canvas = document.createElement("canvas");
ctx = canvas.getContext("2d");
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0);
dataURL = canvas.toDataURL("image/png");
base64 = dataURL.replace(/^data:image\/png;base64,/, "");
return base64;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment