Bash image tools for web designers

[Tweet : ADN : nvALT]

Here are a couple of my Bash functions for people who work with images in CSS or HTML. Nothing elaborate, just things that supplement my typical workflow.

Image dimensions

First, a shell function for quickly getting the pixel dimensions of an image without leaving the shell. This trick can be incorporated into more complex functions in editors or other shell scripts. For example, when I add an image to my blog, a similar trick automatically includes the dimensions in the Jekyll (Liquid) image tag I use.

Add this to your .bash_profile to be able to run imgsize /path/to/image.jpg and get back 600 x 343.

# Quickly get image dimensions from the command line
function imgsize() {
	local width height
	if [[ -f $1 ]]; then
		height=$(sips -g pixelHeight "$1"|tail -n 1|awk '{print $2}')
		width=$(sips -g pixelWidth "$1"|tail -n 1|awk '{print $2}')
		echo "${width} x ${height}"
		echo "File not found"

You can, of course, take the $height and $width variables it creates and modify the output any way you like. You could output a full image tag using <img href="$1" width="$width" height="$height">, too.

Base 64 encoding

I often use data-uri encoding to embed images in my CSS file, both for speed and convenience when distributing. The following function will take an image file as the only argument and place a full CSS background property with a Base64-encoded image in your clipboard, ready for pasting into a CSS file.

# encode a given image file as base64 and output css background property to clipboard
function 64enc() {
	openssl base64 -in $1 | awk -v ext="${1#*.}" '{ str1=str1 $0 }END{ print "background:url(data:image/"ext";base64,"str1");" }'|pbcopy
	echo "$1 encoded to clipboard"

You can also do the same with fonts. I use this to embed a woff file. With a little alteration you can make versions for other formats, but usually when I’m embedding fonts it’s because the stylesheet is being used in a particular context with a predictable browser.

function 64font() {
	openssl base64 -in $1 | awk -v ext="${1#*.}" '{ str1=str1 $0 }END{ print "src:url(\"data:font/"ext";base64,"str1"\")  format(\"woff\");" }'|pbcopy
	echo "$1 encoded as font and copied to clipboard"

Ryan Irelan has produced a series of shell trick videos based on posts. Readers can get 10% off using the coupon code TERPSTRA.