TextMate drag command for Base64 encoding images

[Tweet : ADN : nvALT]

Just a quick hit on this one… when hacking away at the styles of things one probably shouldn’t be hacking away at, embedding images right in the CSS is a handy trick. It’s done by Base64 encoding the image, removing line breaks from the resulting string, and using it to set the background property for the CSS rule.

It looks something like this (truncated):

background:url(data:image/png;base64,iVBORw0KG...AAAAASUVORK5CYII=);

The image/png changes depending on the filetype that’s encoded, becoming image/jpg or image/gif, etc. Anyway, I got tired of shelling out to encode the images, so here’s a very simple command I set up in TextMate which allows me to drag any JPEG, PNG or GIF file into a CSS rule and get the background property with encoded image all at once. Don’t try it with big images, but for the kind of thing you’d actually put into a CSS file, it works great.

The command itself is this (it’s a one-liner):

# Drag command set to handle: jpg,png,gif
# scoped to: text.html.basic source.css.embedded.html, source.css meta.scope.property-list.css

openssl base64 -in "$TM_DROPPED_FILE" | awk -v ext="${TM_DROPPED_FILE#*.}" '{ str1=str1 $0 }END{ print "background:url(data:image/"ext";base64,"str1");" }'

It uses the openssl command that’s on a Mac by default. It encodes the file and outputs it to STDOUT, which is passed to awk. The extension of the dropped file is grabbed via Bash parameter substitution (${TM_DROPPED_FILE#*.}) and passed to awk where it’s subbed in and all of the line breaks are removed. Presto.

Here’s the actual TextMate command if you want to try it out and aren’t sure how to create a new one. Assuming you’re running TextMate (kind of a prerequisite for a TextMate command), just unzip and double click the file.

Base64 Image Encoder TextMate Drag Command v0.9

Encodes a dropped image and inserts a CSS background property with the result in TextMate. Works in embedded CSS and in CSS files.

Updated Sat Jun 19 2010.

More info…