Skip to content

Instantly share code, notes, and snippets.

@gonejack
Last active August 7, 2017 15:52
Show Gist options
  • Save gonejack/2028c43be5010891e21e9cf6939ffd20 to your computer and use it in GitHub Desktop.
Save gonejack/2028c43be5010891e21e9cf6939ffd20 to your computer and use it in GitHub Desktop.
JS :: convert image to data url with javascript
console.clear();
var img = new Image();
img.src = 'img/img.png';
img.onload = function () {
var canvas = document.createElement('canvas'), context = canvas.getContext('2d');
canvas.width = img.width;
canvas.height = img.height;
context.drawImage(img, 0, 0, img.width, img.height);
console.log(canvas.toDataURL('image/png'));
};
function getBase64FromImageUrl(url) {
var img = new Image();
img.setAttribute('crossOrigin', 'anonymous');
img.onload = function () {
var canvas = document.createElement("canvas");
canvas.width =this.width;
canvas.height =this.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(this, 0, 0);
var dataURL = canvas.toDataURL("image/png");
alert(dataURL.replace(/^data:image\/(png|jpg);base64,/, ""));
};
img.src = url;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment