PIL to add colorbars to images

Problem: you have a set of plots, a single image with the color bar for these plots and you want to add the colorbar to each plot, not manually.
Solution: Python Image Library. Making no representations that this represents a particularly elegant or efficient way to do this, here is my solution:

from PIL import Image
import glob
imout = Image.new("RGB",(566,385),(255,255,255))
cim = Image.open("legend.png")
for infile in glob.glob("*plot*.png"):
im = Image.open(infile)
cbar = cim.crop((0,0,127,517))
cbar = cbar.resize((76,385))
plot = im.crop( (0,0,im.size[0],im.size[1]) )
sz = imout.size
pcoords = ( (sz[0]-76),(sz[1]-385),sz[0],sz[1] )
print pcoords
print cbar.size
imout.paste(cbar, pcoords)
imout.paste(plot, (0,0,490,385))

You’ll notice I’ve somewhat lazily hard-coded the dimensions of the colorbar and the plots. legend.png refers to the colorbar, and the glob is used to get a list of all the plots.

Not sure how to get wordpress’ code tag to respect my indentation, but you know what you need to do to make the code work.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: