python tkinter pil 缩略图 脚本

2022-05-13 10:50:43 浏览数 (2)

""" 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)

代码语言:javascript复制
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) imgobj = PhotoImage(file=imgpath) Label(self, image=imgobj).pack() print(imgpath, imgobj.width(), imgobj.height()) # size in pixels self.savephoto = imgobj # keep reference on me

def viewer(imgdir, kind=Toplevel, cols=None): """ make thumb links window for an image directory: one thumb button per image; use kind=Tk to show in main app window, or Frame container (pack); imgfile differs per loop: must save with a default; photoimage objs must be saved: erased if reclaimed; packed row frames (versus grids, fixed-sizes, canvas); """ win = kind() win.title('Viewer: ' imgdir) quit = Button(win, text='Quit', command=win.quit, bg='beige') # pack first quit.pack(fill=X, side=BOTTOM) # so clip last thumbs = makeThumbs(imgdir) if not cols: cols = int(math.ceil(math.sqrt(len(thumbs)))) # fixed or N x N

代码语言:javascript复制
savephotos = []
while thumbs:
    thumbsrow, thumbs = thumbs[:cols], thumbs[cols:]
    row = Frame(win)
    row.pack(fill=BOTH)
    for (imgfile, imgobj) in thumbsrow:
        photo   = PhotoImage(imgobj)
        link    = Button(row, image=photo)
        handler = lambda savefile=imgfile: ViewOne(imgdir, savefile)
        link.config(command=handler)
        link.pack(side=LEFT, expand=YES)
        savephotos.append(photo)
return win, savephotos

if name == 'main': imgdir = (len(sys.argv) > 1 and sys.argv[1]) or 'images' main, save = viewer(imgdir, kind=Tk) main.mainloop()

不保存缩略图

""" same, but make thumb images in memory without saving to or loading from files: seems just as fast for small directories, but saving to files makes startup much quicker for large image collections; saving may be needed in some apps (web pages) """

import os, sys from PIL import Image from tkinter import Tk import viewer_thumbs

def makeThumbs(imgdir, size=(100, 100), subdir='thumbs'): """ create thumbs in memory but don't cache to files """ thumbs = [] for imgfile in os.listdir(imgdir): imgpath = os.path.join(imgdir, imgfile) try: imgobj = Image.open(imgpath) # make new thumb imgobj.thumbnail(size) thumbs.append((imgfile, imgobj)) except: print("Skipping: ", imgpath) return thumbs

if name == 'main': imgdir = (len(sys.argv) > 1 and sys.argv[1]) or 'images' viewer_thumbs.makeThumbs = makeThumbs main, save = viewer_thumbs.viewer(imgdir, kind=Tk) main.mainloop()

0 人点赞