-
-
Save dsignr/0a2b80e281f0258808c89ab48a0226ee to your computer and use it in GitHub Desktop.
Generate Data URI's on the fly
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
// SOURCE: http://davidwalsh.name/convert-image-data-uri-javascript | |
function getDataUri(url, callback) { | |
var image = new Image(); | |
image.onload = function () { | |
var canvas = document.createElement('canvas'); | |
canvas.width = this.naturalWidth; // or 'width' if you want a special/scaled size | |
canvas.height = this.naturalHeight; // or 'height' if you want a special/scaled size | |
canvas.getContext('2d').drawImage(this, 0, 0); | |
// Get raw image data | |
callback(canvas.toDataURL('image/png').replace(/^data:image\/(png|jpg);base64,/, '')); | |
// ... or get as Data URI | |
callback(canvas.toDataURL('image/png')); | |
}; | |
image.src = url; | |
} | |
// Usage | |
getDataUri('/logo.png', function(dataUri) { | |
// Do whatever you'd like with the Data URI! | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment