Skip to content

Instantly share code, notes, and snippets.

@bittu
Created July 26, 2016 11:59
Show Gist options
  • Save bittu/3edbca5ae9539565cc8fdc103d355b8e to your computer and use it in GitHub Desktop.
Save bittu/3edbca5ae9539565cc8fdc103d355b8e to your computer and use it in GitHub Desktop.
Javascript: Image to base64 data URL
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