Skip to content

Instantly share code, notes, and snippets.

@cawa87
Last active August 26, 2021 07:36
Show Gist options
  • Save cawa87/1c477d44fcfdf67aea3f to your computer and use it in GitHub Desktop.
Save cawa87/1c477d44fcfdf67aea3f to your computer and use it in GitHub Desktop.
JavaScript Convert an image to a base64 url
/**
* Convert an image
* to a base64 url
* @param {String} url
* @param {Function} callback
* @param {String} [outputFormat=image/png]
*/
function convertImgToBase64URL(url, callback, outputFormat){
var img = new Image();
img.crossOrigin = 'Anonymous';
img.onload = function(){
var canvas = document.createElement('CANVAS'),
ctx = canvas.getContext('2d'), dataURL;
canvas.height = img.height;
canvas.width = img.width;
ctx.drawImage(img, 0, 0);
dataURL = canvas.toDataURL(outputFormat);
callback(dataURL);
canvas = null;
};
img.src = url;
}

Usage

convertImgToBase64URL('http://bit.ly/18g0VNp', function(base64Img){
    // Base64DataURL
});
@dpr10
Copy link

dpr10 commented Sep 12, 2019

👍

@amoghs
Copy link

amoghs commented Oct 16, 2019

thanks!

@uesleisuptitz
Copy link

Muito bom! Era justamente o que eu precisava! Obrigado!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment