-
-
Save builtbylane/0804fbf3aa4a6c4744f4 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| /** | |
| * Converts an image to | |
| * a base64 string. | |
| * | |
| * @param {String} url | |
| * @param {Function} callback | |
| * @param {String} [outputFormat='image/png'] | |
| * @author HaNdTriX | |
| * @example | |
| * convertImgToBase64('http://goo.gl/AOxHAL', function(err, base64Img){ | |
| * console.log('IMAGE:',base64Img); | |
| * }) | |
| */ | |
| function convertImgToBase64(url, callback, outputFormat){ | |
| 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 || 'image/png'); | |
| 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