Skip to content

Instantly share code, notes, and snippets.

@sivsivsree
Last active November 20, 2017 10:28
Show Gist options
  • Save sivsivsree/94bb6548797bc894b96e to your computer and use it in GitHub Desktop.
Save sivsivsree/94bb6548797bc894b96e to your computer and use it in GitHub Desktop.
/**
* @author Siv.S
* @date 03/may/2014 at 11:32
*
* convertImgToBase64
* @param {String} url
* @param {Function} callback
* @param {String} [outputFormat='image/png']
* @author HaNdTriX
* @example
convertImgToBase64('http://goo.gl/AOxHAL', function(base64Img){
console.log('IMAGE:',base64Img);
})
*/
function convertImgToBase64(url, callback, outputFormat){
var canvas = document.createElement('CANVAS');
var ctx = canvas.getContext('2d');
var img = new Image;
img.crossOrigin = 'Anonymous';
img.onload = function(){
canvas.height = img.height;
canvas.width = img.width;
ctx.drawImage(img,0,0);
var dataURL = canvas.toDataURL(outputFormat || 'image/png');
callback.call(this, dataURL);
// Clean up
canvas = null;
};
img.src = url;
}
@sivsivsree
Copy link
Author

convertImgToBase64()

This can be used to convert a png image to datauri so as to make the javascript file upload easier!

Note: works only on browsers which supports the Canvas Elements

Thanks, Siv.S a.k.a Sivsivsree

facebook : http://fb.me/sivsivsree

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