python pyphoto图片查看器

image.png

"""
############################################################################
PyPhoto 1.1: thumbnail image viewer with resizing and saves.

Supports multiple image directory thumb windows - the initial img dir
is passed in as cmd arg, uses "images" default, or is selected via main
window button; later directories are opened by pressing "D" in image view
or thumbnail windows.

Viewer also scrolls popped-up images that are too large for the screen;
still to do: (1) rearrange thumbnails when window resized, based on current
window size; (2) [DONE] option to resize images to fit current window size?
(3) avoid scrolls if image size is less than window max size: use Label
if imgwide <= scrwide and imghigh <= scrhigh?

New in 1.1: updated to run in Python 3.1 and latest PIL;

New in 1.0: now does a form of (2) above: image is resized to one of the
display's dimensions if clicked, and zoomed in or out in 10% increments
on key presses; generalize me; caveat: seems to lose quality, pixels
after many resizes (this is probably a limitation of PIL)

The following scaler adapted from PIL's thumbnail code is similar to the
screen height scaler here, but only shrinks:
x, y = imgwide, imghigh
if x > scrwide: y = max(y * scrwide // x, 1); x = scrwide
if y > scrhigh: x = max(x * scrhigh // y, 1); y = scrhigh
############################################################################
"""

import sys, math, os
from tkinter import *
from tkinter.filedialog import SaveAs, Directory

from PIL import Image # PIL Image: also in tkinter
from PIL.ImageTk import PhotoImage # PIL photo widget replacement

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

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

remember last dirs across all windows

saveDialog = SaveAs(title='Save As (filename gives image type)')
openDialog = Directory(title='Select Image Directory To Open')

trace = print # or lambda *x: None
appname = 'PyPhoto 1.1: '

class ScrolledCanvas(Canvas):
"""
a canvas in a container that automatically makes
vertical and horizontal scroll bars for itself
"""
def init(self, container):
Canvas.init(self, container)
self.config(borderwidth=0)
vbar = Scrollbar(container)
hbar = Scrollbar(container, orient='horizontal')

    vbar.pack(side=RIGHT,  fill=Y)                 # pack canvas after bars
    hbar.pack(side=BOTTOM, fill=X)                 # so clipped first
    self.pack(side=TOP, fill=BOTH, expand=YES)

    vbar.config(command=self.yview)                # call on scroll move
    hbar.config(command=self.xview)
    self.config(yscrollcommand=vbar.set)           # call on canvas move
    self.config(xscrollcommand=hbar.set)

class ViewOne(Toplevel):
"""
open a single image in a pop-up window when created;
a class because photoimage obj must be saved, else
erased if reclaimed; scroll if too big for display;
on mouse clicks, resizes to window's height or width:
stretches or shrinks; on I/O keypress, zooms in/out;
both resizing schemes maintain original aspect ratio;
code is factored to avoid redundancy here as possible;
"""
def init(self, imgdir, imgfile, forcesize=()):
Toplevel.init(self)
helptxt = '(click L/R or press I/O to resize, S to save, D to open)'
self.title(appname + imgfile + ' ' + helptxt)
imgpath = os.path.join(imgdir, imgfile)
imgpil = Image.open(imgpath)
self.canvas = ScrolledCanvas(self)
self.drawImage(imgpil, forcesize)
self.canvas.bind('<Button-1>', self.onSizeToDisplayHeight)
self.canvas.bind('<Button-3>', self.onSizeToDisplayWidth)
self.bind('<KeyPress-i>', self.onZoomIn)
self.bind('<KeyPress-o>', self.onZoomOut)
self.bind('<KeyPress-s>', self.onSaveImage)
self.bind('<KeyPress-d>', onDirectoryOpen)
self.focus()

def drawImage(self, imgpil, forcesize=()):
    imgtk = PhotoImage(image=imgpil)                 # not file=imgpath
    scrwide, scrhigh = forcesize or self.maxsize()   # wm screen size x,y
    imgwide  = imgtk.width()                         # size in pixels
    imghigh  = imgtk.height()                        # same as imgpil.size

    fullsize = (0, 0, imgwide, imghigh)              # scrollable
    viewwide = min(imgwide, scrwide)                 # viewable
    viewhigh = min(imghigh, scrhigh)

    canvas = self.canvas
    canvas.delete('all')                             # clear prior photo
    canvas.config(height=viewhigh, width=viewwide)   # viewable window size
    canvas.config(scrollregion=fullsize)             # scrollable area size
    canvas.create_image(0, 0, image=imgtk, anchor=NW)

    if imgwide <= scrwide and imghigh <= scrhigh:    # too big for display?
        self.state('normal')                         # no: win size per img
    elif sys.platform[:3] == 'win':                  # do windows fullscreen
        self.state('zoomed')                         # others use geometry()
    self.saveimage = imgpil
    self.savephoto = imgtk                           # keep reference on me
    trace((scrwide, scrhigh), imgpil.size)

def sizeToDisplaySide(self, scaler):
    # resize to fill one side of the display
    imgpil = self.saveimage
    scrwide, scrhigh = self.maxsize()                 # wm screen size x,y
    imgwide, imghigh = imgpil.size                    # img size in pixels
    newwide, newhigh = scaler(scrwide, scrhigh, imgwide, imghigh)
    if (newwide * newhigh < imgwide * imghigh):
        filter = Image.ANTIALIAS                      # shrink: antialias
    else:                                             # grow: bicub sharper
        filter = Image.BICUBIC
    imgnew  = imgpil.resize((newwide, newhigh), filter)
    self.drawImage(imgnew)

def onSizeToDisplayHeight(self, event):
    def scaleHigh(scrwide, scrhigh, imgwide, imghigh):
        newhigh = scrhigh
        newwide = int(scrhigh * (imgwide / imghigh))        # 3.x true div
        return (newwide, newhigh)                           # proportional
    self.sizeToDisplaySide(scaleHigh)

def onSizeToDisplayWidth(self, event):
    def scaleWide(scrwide, scrhigh, imgwide, imghigh):
        newwide = scrwide
        newhigh = int(scrwide * (imghigh / imgwide))        # 3.x true div
        return (newwide, newhigh)
    self.sizeToDisplaySide(scaleWide)

def zoom(self, factor):
    # zoom in or out in increments
    imgpil = self.saveimage
    wide, high = imgpil.size
    if factor < 1.0:                     # antialias best if shrink
        filter = Image.ANTIALIAS         # also nearest, bilinear
    else:
        filter = Image.BICUBIC
    new = imgpil.resize((int(wide * factor), int(high * factor)), filter)
    self.drawImage(new)

def onZoomIn(self, event, incr=.10):
    self.zoom(1.0 + incr)

def onZoomOut(self, event, decr=.10):
    self.zoom(1.0 - decr)

def onSaveImage(self, event):
    # save current image state to file
    filename = saveDialog.show()
    if filename:
       self.saveimage.save(filename)

def onDirectoryOpen(event):
"""
open a new image directory in new pop up
available in both thumb and img windows
"""
dirname = openDialog.show()
if dirname:
viewThumbs(dirname, kind=Toplevel)

def viewThumbs(imgdir, kind=Toplevel, numcols=None, height=400, width=500):
"""
make main or pop-up thumbnail buttons window;
uses fixed-size buttons, scrollable canvas;
sets scrollable (full) size, and places
thumbs at abs x,y coordinates in canvas;
no longer assumes all thumbs are same size:
gets max of all (x,y), some may be smaller;
"""
win = kind()
helptxt = '(press D to open other)'
win.title(appname + imgdir + ' ' + helptxt)
quit = Button(win, text='Quit', command=win.quit, bg='beige')
quit.pack(side=BOTTOM, fill=X)
canvas = ScrolledCanvas(win)
canvas.config(height=height, width=width) # init viewable window size
# changes if user resizes
thumbs = makeThumbs(imgdir) # [(imgfile, imgobj)]
numthumbs = len(thumbs)
if not numcols:
numcols = int(math.ceil(math.sqrt(numthumbs))) # fixed or N x N
numrows = int(math.ceil(numthumbs / numcols)) # 3.x true div

# max w|h: thumb=(name, obj), thumb.size=(width, height)
linksize = max(max(thumb[1].size) for thumb in thumbs)
trace(linksize)
fullsize = (0, 0,                                   # upper left  X,Y
    (linksize * numcols), (linksize * numrows) )    # lower right X,Y
canvas.config(scrollregion=fullsize)                # scrollable area size

rowpos = 0
savephotos = []
while thumbs:
    thumbsrow, thumbs = thumbs[:numcols], thumbs[numcols:]
    colpos = 0
    for (imgfile, imgobj) in thumbsrow:
        photo   = PhotoImage(imgobj)
        link    = Button(canvas, image=photo)
        def handler(savefile=imgfile):
            ViewOne(imgdir, savefile)
        link.config(command=handler, width=linksize, height=linksize)
        link.pack(side=LEFT, expand=YES)
        canvas.create_window(colpos, rowpos, anchor=NW,
                window=link, width=linksize, height=linksize)
        colpos += linksize
        savephotos.append(photo)
    rowpos += linksize
win.bind('<KeyPress-d>', onDirectoryOpen)
win.savephotos = savephotos
return win

if name == 'main':
"""
open dir = default or cmdline arg
else show simple window to select
"""
imgdir = 'images'
if len(sys.argv) > 1: imgdir = sys.argv[1]
if os.path.exists(imgdir):
mainwin = viewThumbs(imgdir, kind=Tk)
else:
mainwin = Tk()
mainwin.title(appname + 'Open')
handler = lambda: onDirectoryOpen(None)
Button(mainwin, text='Open Image Directory', command=handler).pack()
mainwin.mainloop()

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 201,681评论 5 474
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 84,710评论 2 377
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 148,623评论 0 334
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,202评论 1 272
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,232评论 5 363
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,368评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,795评论 3 393
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,461评论 0 256
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,647评论 1 295
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,476评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,525评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,226评论 3 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,785评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,857评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,090评论 1 258
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,647评论 2 348
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,215评论 2 341

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,278评论 0 10
  • The Inner Game of Tennis W Timothy Gallwey Jonathan Cape ...
    网事_79a3阅读 11,648评论 2 19
  • mean to add the formatted="false" attribute?.[ 46% 47325/...
    ProZoom阅读 2,689评论 0 3
  • 首先,祝自己生日快乐啦~ 一直很看重节日生日这些纪念日 因为觉得每个人的出生都应该得到祝福 这次又是二十周岁生日 ...
    forever21rachel阅读 251评论 0 0
  • 布满繁星的夜美的那样妖娆,大抵是因为白天的晴空万里,月光和灯光编织着回家的路,我和你们在忙碌的补习后牵手走在月光之...
    亭子驿站阅读 314评论 0 1