Android: 9 patching a family of images the easy way

9 patch images in Android are great but if you happen to have a family of graphics to convert, it can get pretty tedious. I had a collection of button graphics that needed converting to 9 patches using the same stretchable regions.

Rather than do it all by hand with Photoshop or GIMP (and inevitably need to redo them all again later when something needed changing) I wrote a small BASH script to do it.

To use the script, first use the draw9patch tool to create the 9 patch info for one of your graphics – this will become the template. Once you’re done, go:

[code language=”bash” light=”true”]
./9batch.sh template.9.png button2.png button3.png …
[/code]

to copy the 1 pixel border from the template to your remaining graphics and save a .9.png version of each of them.

Note that you’ll need to install ImageMagick to use the 9batch script:

[code language=”bash” light=”true”]
sudo apt-get install imagemagick
[/code]

Apparently WordPress won’t let me upload the script itself so here’s the source code:

[code language=”bash” light=”true” collapse=”true”]
#!/bin/bash

if [ "$#" -lt 2 ]; then
echo "Usage: 9batch.sh template image1 image2 …" >&2
echo
echo "Applies 9 patch info to a family of images using one image as the template" >&2
echo "Template image should be 2 pixels wider and higher than source images" >&2
exit 1
fi

# 9 patch image to use as template
src=$1

for i in ${@:2}
do
# use sed to change extension from .png to .9.png and assign result to ‘out’
out=`echo $i | sed -e ‘s:\(….\)$:.9\1:’`
composite -gravity center $i $src $out
done
[/code]

Leave a Reply

Your email address will not be published.