Example Thumbnail Index Image

In a previous example we've created a catalog of images. While that catalog is quite useful, it doesn't show the contents of those images. A more useful catalog perhaps would be a collage of the images annotated with text showing each image's file name (see Listing 9-7).

Listing 9-7. Thumbnail Index Image

# thumbnail index import os from PIL import Image, ImageDraw def thumbnail_index(dirpath):

Create a thumbnail index from images in dirpath

cat_size = (num_images*thumb_size[o], num_images*thumb_size[l])

# go through all the pictures in a directory for file in os.listdir(dirpath):

# get the pathname for the file pathname = os.path.join(dirpath, file)

# open the image file img = Image.open(pathname)

except IOError:

print file, "is not an image file" continue

# create a thumbnail img.thumbnail((thumb_size), Image.ANTIALIAS) draw = ImageDraw.Draw(img) draw.text((2, 2), file)

# do we need to create a new catalog image? if img_index == 0:

# calculate the location for this image x = img_index % num_images y = img_index II num_images fn_index = 0 img_index = 0

# file name index

# image index

# paste the thumbnail thumbs_img.paste(img, (x*thumb_size[o], y*thumb_size[l]))

# increment the image index img_index += 1

# have we reached the end of the catalog image? if img_index == num_images**2:

thumbs_img.save('%s-%03d.cat.jpg' % (dirpath, fn_index)) fn_index += 1

# save the last catalog file if img_index:

thumbs_img.save('%s-%03d.cat.jpg' % (dirpath, fn_index))

The function thumnail_index() accepts a directory and produces a thumbnail index image. Figure 9-4 shows the result from running the function on a collection of images my daughter particularly likes.

Tkinter Examples Python
Figure 9-4. Thumbnail index image

For the purpose of this example, I decided not to use os.walk() and iterate through the directory listing, instead using os.listdir(). I've defined two parameters: numimages, which holds the number of images on either x- or y-axis, and thumbsize, which holds the thumbnail width and height. Next I composed a list of all the files in the requested directory. For every file, the script tries to open the file as if it were an image file. If indeed a file is an image file, a thumbnail of the image is created and pasted to the index image. Additionally, the thumbnail is annotated with the file name in the top-left corner. There's some indexing used to determine the exact location of an image in the thumbnail index image as well as creating a new thumbnail index image once the current one has filled up.

Was this article helpful?

0 0

Post a comment