Skip to content

Instantly share code, notes, and snippets.

@paultreny
Forked from HaNdTriX/image_to_data_url.js
Created March 22, 2014 22:21
Show Gist options
  • Save paultreny/9715332 to your computer and use it in GitHub Desktop.
Save paultreny/9715332 to your computer and use it in GitHub Desktop.
/**
* Converts an image to
* a base64 string.
*
* If you want to use the
* outputFormat or quality param
* I strongly recommend you read the docs
* @ mozilla for `canvas.toDataURL()`
*
* @param {String} url
* @param {Function} callback
* @param {String} [outputFormat='image/png']
* @param {Float} [quality=0.0 to 1.0]
* @url https://gist.github.com/HaNdTriX/7704632/
* @docs https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement#Methods
* @author HaNdTriX
* @example
* imgToDataURL('http://goo.gl/AOxHAL', function(err, base64Img){
* console.log('IMAGE:',base64Img);
* })
*/
function imgToDataURL(url, callback, outputFormat, quality) {
var canvas = document.createElement('CANVAS'),
ctx = canvas.getContext('2d'),
img = new Image();
img.crossOrigin = 'Anonymous';
img.onload = function() {
var dataURL;
canvas.height = img.height;
canvas.width = img.width;
try {
ctx.drawImage(img, 0, 0);
dataURL = canvas.toDataURL(outputFormat, quality);
callback(null, dataURL);
} catch (e) {
callback(e, null);
}
canvas = img = null;
};
img.onerror = function() {
callback(new Error('Could not load image'), null);
};
img.src = url;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment