Base64-Encoding Images for CSS in TextMate

• ~200 words • 1 minute read

Base64-encoding your images reduces the number of HTTP requests your page makes by effectively embedding the image in your HTML or CSS. It is particularly useful for logos, backgrounds and UI elements where you want to avoid the progressive loading effect that happens when the user first visits the page.

There are plenty of scripts out there that show you how to base64 encode a file, but I thought it would be handier to make a TextMate command. Now when I'm editing my CSS I can reference the actual image files as I normally might, which is easier to understand at a glance, and base64-encode them as I need to with this command.

To get started, open up the Bundle Editor and create a new command that looks like this:

#!/usr/bin/env php <?php $line = $_ENV["TM_CURRENT_LINE"]; $pattern = "/url(([a-zA-Z.-_/0-9]+))/";


$file = $matches[1]; $contents = file_get_contents($file); $mime = mime_content_type($file); $new_line = "data:$mime;base64,".base64_encode($contents);

echo str_replace($file, $newLine,$line);

What this will do is take the input on the current line you have selected and replace any url(example.jpg) images with the base64 encoded equivalent. Basically, this:

background: url(../images/stripe.png);

Becomes this:

background: url(data:image/png;base64,iVBORw0KGg...);

It will preserve the mime-type, which is convenient. If you wanted to take it a step further you could adapt the code to look for src="" and use it to encode images, JavaScript and even CSS files in your HTML as well.