Convert Image to Data URI with JavaScript
Whenever I go on a "performance run" on a website, the first place I look is imagery. Why? Because you can save an image out of Photoshop, push it into ImageOptim or even TinyPNG, and save 70% on its file size. What do most developers not consider? Taking tiny image files and making them data URIs instead of traditional images (another HTTP request). Unfortunately that needs to happen on the CSS file before page load, but you need to get that data URI from somewhere, right?
I'm a bit suspicious of random websites which allow you upload files or content and return a given result; you don't know the author of said code. So I've gone to my own code, modifying it a bit along the way, to create a utility for converting an image to data URI!
Convert Image to Data URI
Like my original post, we need to rely on canvas to do the heavy lifting:
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! });
You could also set this up to use Promises instead of a callback.
Once the image has loaded, we thrust it into canvas and then export its data to a data URI. In practical terms, this isn't a useful task since the image has already loaded but if you're looking to create a local utility to perform this task, here you go!
0 comentarios:
Publicar un comentario