Last active
November 20, 2017 10:28
-
-
Save sivsivsree/94bb6548797bc894b96e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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