Skip to content

Instantly share code, notes, and snippets.

@MeTe-30
Created December 6, 2016 08:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MeTe-30/9f853178f8beb65c42afa033e91bead3 to your computer and use it in GitHub Desktop.
Save MeTe-30/9f853178f8beb65c42afa033e91bead3 to your computer and use it in GitHub Desktop.
Convert image to Base64, dataUrl by Canvas & BLOB | Javscript
function toDataUrl(url, callback) {
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = function () {
var reader = new FileReader();
reader.onloadend = function () {
callback(reader.result);
}
reader.readAsDataURL(xhr.response);
};
xhr.open('GET', url);
xhr.send();
}
function toDataUrl(url, callback) {
var image = new Image();
image.setAttribute('crossOrigin', 'anonymous');
image.onload = function () {
var canvas = document.createElement('canvas');
canvas.width = this.naturalWidth;
canvas.height = this.naturalHeight;
canvas.getContext('2d').drawImage(this, 0, 0, canvas.width, canvas.height);
callback(canvas.toDataURL('image/png', 1));
};
image.src = url;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment