Skip to content

Instantly share code, notes, and snippets.

@bonniss
Forked from cawa87/base64.js
Created July 14, 2019 03:36
Show Gist options
  • Save bonniss/4099b28755b7ee51551afd972ad2e152 to your computer and use it in GitHub Desktop.
Save bonniss/4099b28755b7ee51551afd972ad2e152 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
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment