Created
July 26, 2016 11:59
-
-
Save bittu/3edbca5ae9539565cc8fdc103d355b8e to your computer and use it in GitHub Desktop.
Javascript: Image to base64 data URL
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
function toDataUrl(src, type, callback) { | |
const img = new Image(); | |
img.onload = function() { | |
const canvas = document.createElement('canvas'); | |
const ctx = canvas.getContext('2d'); | |
canvas.height = this.height; | |
canvas.width = this.width; | |
ctx.drawImage(this, 0, 0); | |
callback(canvas.toDataURL(type)); | |
} | |
img.onerror = function() { | |
callback('') | |
} | |
img.src = src; | |
} | |
let imgs = ['image1.jpg', 'image2.jpg'] | |
let convertedImages = []; | |
imgs.forEach((v) => { | |
toDataUrl(v, 'jpeg', (d) => { | |
convertedImages.push(d); | |
}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment