Skip to content

Instantly share code, notes, and snippets.

@garth
Created November 23, 2011 15:29
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save garth/1388969 to your computer and use it in GitHub Desktop.
Save garth/1388969 to your computer and use it in GitHub Desktop.
Convert url image ref into inline base 64 in css with nodejs
var css = 'insert lots of css here';
var files = {};
css = css.replace(/url\((\S*)\.(png|jpg|jpeg|gif)\)/g, function(match, file, type)
{
var fileName = file + '.' + type;
var size = fs.statSync(fileName).size;
if (size > 4096) {
console.log('Skipping ' + fileName + ' (' + (Math.round(size/1024*100)/100) + 'k)');
return match;
}
else {
var base64 = fs.readFileSync(fileName).toString('base64');
if (typeof(files[fileName]) !== 'undefined') {
console.log('Warning: ' + fileName + ' has already been base64 encoded in the css');
}
files[fileName] = true;
return 'url("data:image/' + (type === 'jpg' ? 'jpeg' : type) + ';base64,' + base64 + '")';
}
});
@garth
Copy link
Author

garth commented Nov 23, 2011

This gist uses fs.readFileSync() because it is used as part of the build process (Jakefile.js), if you want to use it from within a production web server, then it should be changed to non-blocking and add caching.

@garth
Copy link
Author

garth commented Dec 5, 2011

Updated to skip images > 4k

@plivox
Copy link

plivox commented Apr 26, 2012

Thank you very much for this post 'garth', here is an example with Lessjs:

(function(tree, dirname) {
    tree.functions.base64 = function(argument) {
        return new(tree.Anonymous)((function(filename, quote) {
            var dist = 'url(' + quote + filename + quote + ')';

            // Search types supported.
            if (match = filename.match(/\.(png|jpg|jpeg|gif)/)) {
                var image = path.normalize(dirname + '/' + filename),
                    type = match[1];

                try {
                    if ((fs.statSync(image).size) > 4096)
                        return dist;

                    return 'url(' + quote + 'data:image/' + (type === 'jpg' ? 'jpeg' : type) + 
                                ';base64,' + fs.readFileSync(image).toString('base64') + quote + ')';

                } catch(err) {
                    return 'none';
                }
            } else {
                return dist;
            }
        })(argument.value, argument.quote));
    }
})(less.tree, __dirname + '/../../public');

If it can help;)

@jreading
Copy link

jreading commented Jan 2, 2013

https://gist.github.com/4437292

Edited to allow for single or double quotes:

css = css.replace(/url\(["']?(\S*)\.(png|jpg|jpeg|gif)["']?\)/g, function(match, file, type)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment