Skip to content

Instantly share code, notes, and snippets.

@rpmuller
Created July 12, 2013 20:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rpmuller/5987507 to your computer and use it in GitHub Desktop.
Save rpmuller/5987507 to your computer and use it in GitHub Desktop.
Create a simple contact sheet from a list of image filenames.
def make_contact_sheet(fnames,(ncols,nrows),(photow,photoh),
(marl,mart,marr,marb),
padding):
"""\
Make a contact sheet from a group of filenames:
fnames A list of names of the image files
ncols Number of columns in the contact sheet
nrows Number of rows in the contact sheet
photow The width of the photo thumbs in pixels
photoh The height of the photo thumbs in pixels
marl The left margin in pixels
mart The top margin in pixels
marr The right margin in pixels
marl The left margin in pixels
padding The padding between images in pixels
returns a PIL image object.
"""
# Read in all images and resize appropriately
imgs = [Image.open(fn).resize((photow,photoh)) for fn in fnames]
# Calculate the size of the output image, based on the
# photo thumb sizes, margins, and padding
marw = marl+marr
marh = mart+ marb
padw = (ncols-1)*padding
padh = (nrows-1)*padding
isize = (ncols*photow+marw+padw,nrows*photoh+marh+padh)
# Create the new image. The background doesn't have to be white
white = (255,255,255)
inew = Image.new('RGB',isize,white)
# Insert each thumb:
for irow in range(nrows):
for icol in range(ncols):
left = marl + icol*(photow+padding)
right = left + photow
upper = mart + irow*(photoh+padding)
lower = upper + photoh
bbox = (left,upper,right,lower)
try:
img = imgs.pop(0)
except:
break
inew.paste(img,bbox)
return inew
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment