URI Encoding an image

by jenny on 19 June 2009 - 04:34pm in

I've known for some time that it's possible to embed an image into CSS (useful for greasemonkey scripts), using a format like so:


...where [mimetype] is the mime type of your data (eg, image/png).

It's eluded me until now how exactly to get at the [data] bit of this equation. This is simply the base64 encoded string of the actual bytes of the file, which you can get like so:

cat foo.png | base64

This will spit a bunch of garbage to your screen, which you copy and paste into the [data] placeholder.

Example usage in css:

div.question { background-image: url(data:image/gif;base64,R0lGODlhDQAOAJEAANno6wBmZgAAAAAAACH5BAAAAAAALAAAAAANAA4AQAIjjI8Iyw3GhACSQecutsFV3nzgNi7SVEbo06lZa66LRib2UQAAOw%3D%3D) }

The output is often much longer than this example and I like to pipe it to perl to remove the newlines... not sure if that's actually necessary.

cat foo.png | base64 | perl -pe 'chomp'