Created
May 5, 2016 03:39
-
-
Save kfitfk/ef3e4d4327979a690706c6d6614e83b3 to your computer and use it in GitHub Desktop.
Convert an image to base64 encoding
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
/** | |
* Convert an image to a base64 encoded value | |
* @param {string} url - The url of the image which has correct Access-Control-Allow-Origin response header | |
* @param {function} callback - callback with one parameter containing the base64 encoded value | |
* @param {string} [outputFormat] - image/png or image/jpeg or image/webp(Chrome) | |
*/ | |
function convertImgToBase64(url, callback, outputFormat){ | |
var img = new Image() | |
img.crossOrigin = 'Anonymous' | |
img.onload = function() { | |
var canvas = document.createElement('canvas') | |
var ctx = canvas.getContext('2d') | |
var dataURL | |
canvas.height = this.height | |
canvas.width = this.width | |
ctx.drawImage(this, 0, 0) | |
dataURL = canvas.toDataURL(outputFormat) | |
callback(dataURL) | |
canvas = null | |
} | |
img.src = url | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment