Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@kfitfk
Created May 5, 2016 03:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kfitfk/ef3e4d4327979a690706c6d6614e83b3 to your computer and use it in GitHub Desktop.
Save kfitfk/ef3e4d4327979a690706c6d6614e83b3 to your computer and use it in GitHub Desktop.
Convert an image to base64 encoding
/**
* 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