gVim / MacVim drag command for base64 encoding images

The idea is that it can be very useful to base64 encode an image directly into your css file instead of referencing a separate file, but doing so usually involves dropping to the command line, calling openssl, copy-pasting the output, specifying the mime-type, etc… Bret’s Terpstra distilled all of that into one drag-and-drop command for Textmate.The following is simply a generalization and instructions for using the drag and drop in MacVim / GVim

First, take the following and make it into an executable somewhere in your path. That way you can use it from any app that can interact with the command line. I called the fill css_image

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

It’ll generate something like this (only much longer):


Now, to call it from MacVim and have the output inserted into your file simply switch to command mode and type

:r ! css_image

leave a trailing space and drag the file into MacVim and hit enter. Dragging it on when in this state will cause the path to the image to be inserted. Enter causes the command to be executed, and the output to be inserted into your file.