reuse the makeThumbs function here repeatedly in other examples. As usual, these are
some of the primary benefits inherent in open source software in general.
Example 8-45. PP4E\Gui\PIL\viewer_thumbs.py
"""
display all images in a directory as thumbnail image buttons that display
the full image when clicked; requires PIL for JPEGs and thumbnail image
creation; to do: add scrolling if too many thumbs for window!
"""
import os, sys, math
from tkinter import *
from PIL import Image # <== required for thumbs
from PIL.ImageTk import PhotoImage # <== required for JPEG display
def makeThumbs(imgdir, size=(100, 100), subdir='thumbs'):
"""
get thumbnail images for all images in a directory; for each image, create
and save a new thumb, or load and return an existing thumb; makes thumb
dir if needed; returns a list of (image filename, thumb image object);
caller can also run listdir on thumb dir to load; on bad file types may
raise IOError, or other; caveat: could also check file timestamps;
"""
thumbdir = os.path.join(imgdir, subdir)
if not os.path.exists(thumbdir):
os.mkdir(thumbdir)
thumbs = []
for imgfile in os.listdir(imgdir):
thumbpath = os.path.join(thumbdir, imgfile)
if os.path.exists(thumbpath):
thumbobj = Image.open(thumbpath) # use already created
thumbs.append((imgfile, thumbobj))
else:
print('making', thumbpath)
imgpath = os.path.join(imgdir, imgfile)
try:
imgobj = Image.open(imgpath) # make new thumb
imgobj.thumbnail(size, Image.ANTIALIAS) # best downsize filter
imgobj.save(thumbpath) # type via ext or passed
thumbs.append((imgfile, imgobj))
except: # not always IOError
print("Skipping: ", imgpath)
return thumbs
class ViewOne(Toplevel):
"""
open a single image in a pop-up window when created; photoimage
object must be saved: images are erased if object is reclaimed;
"""
def init(self, imgdir, imgfile):
Toplevel.init(self)
self.title(imgfile)
imgpath = os.path.join(imgdir, imgfile)
Viewing and Processing Images with PIL | 497