Skip to content

Instantly share code, notes, and snippets.

@dsignr
Forked from psema4/datauri-generator.js
Created August 11, 2016 03:48
Show Gist options
  • Save dsignr/0a2b80e281f0258808c89ab48a0226ee to your computer and use it in GitHub Desktop.
Save dsignr/0a2b80e281f0258808c89ab48a0226ee to your computer and use it in GitHub Desktop.
Generate Data URI's on the fly
// 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