ZIP書庫内のjpegを表示(Pythonで)

昨日はモジュールzipfileやos.walk関数のチュートリアルを読んでおりました。で、適当に何かこさえよう、ということで、zip書庫中のjpegを表示する画像ビュアーを作ってみることに。

<<追記>>
・zipfileがファイルを開きっぱなしにするようなのでcloseする処理を追加。
・今回は単純なリストだけで十分なので、組み込み関数iterを使うように。iglobとか、os.walkなどのジェネレータを使うとiterじゃダメなんですけれども。
・2回目以降は最後にアクセスしたフォルダを表示
・えらく長くなってしまった。。。

#! /usr/bin/env python

from zipfile import ZipFile
import tkFileDialog

from Tkinter import *
import PIL.Image, PIL.ImageTk
import tkFileDialog
from StringIO import StringIO
from glob import iglob
import os.path
"""
def gfactory(l):
    def f(g=(x for x in l)):
        for x in g:
            return x
    return f      
"""##今回は組み込み関数のiterで十分でした
class App(Frame):
    lastdir=""
    idx=0 ; l=[] ; zf=None ; fp=None
    #dustbox=[]
    #nextf=gfactory([])
    nextf=iter([])
    def quit(self, event): self.master.destroy()

    def open(self, event=None):
        if not self.zf or not self.l :
            if not self.initz(): return 
        if event :
            try:
                self.fp=self.nextf() ;            
            except StopIteration : 
                self.initz()
                try:
                    self.fp=self.nextf()
                except StopIteration :
                    return
        if not self.fp or not self.zf : return
        z=StringIO(self.zf.read(self.fp))
        im=self.im = PIL.Image.open(z,"r")
        if not self.wide_flag:
            im.draft("RGB",(100,100))
        if im.mode == "1": # bitmap image
            self.image1 = PIL.ImageTk.BitmapImage(im, foreground="white")
        else:              # photo image
            self.image1 = PIL.ImageTk.PhotoImage(im)
            self.la.config(image=self.image1,
            width=self.image1.width(), height=self.image1.height())
    def openwide(self,event):
        if self.fp:
            self.wide_flag = not self.wide_flag
            self.open()
    def initz3(self,event=None):
        if self.initz() :
            self.open(1)        
    def initz(self):
        
        filename =tkFileDialog.askopenfilename(
                                     initialdir=self.lastdir)
        if filename : self.lastdir=os.path.abspath(
                                os.path.dirname(filename))
        if  filename.split(".")[-1]=="zip":
            if self.zf :
                try:
                    #dustbox.append(self.zf.fp)
                    self.zf.fp.close()
                    #self.zf.close();
                    self.zf=None;
                    del self.zf
                except: pass
            self.zf=ZipFile(filename,"r")
            self.l=[x for x in self.zf.namelist()  if x.split(".")[-1] in "bmp jpg jpeg png gif"]
            if self.l :
                self.nextf=iter(self.l).next
              #self.nextf=gfactory(l)
        #今回は組み込み関数のiterで十分でした
            else :               
                if self.zf :
                    try:
                        dustbox.append(self.zf.fp)
                        self.zf.fp.close()
                        #self.zf.close() #要る?
                    except: pass
                    del self.zf; self.zf=None;
        else : self.nextf=iter(self.l).next
        return self.l
        
    def init (self):
        self.image1 = PhotoImage()
        la = self.la = Label(self, image=self.image1, bg="#000000",
                         width=100, height=100)
        la.bind("<Button-1>", self.open)
        la.bind("<Button-2>", self.openwide)
        la.bind("<Button-3>", self.initz3)
        la.pack()

    def __init__(self, master=None):

        self.wide_flag=True;
        Frame.__init__(self, master)
        self.master.title('PIL ZIP Slide Show')
        self.init(); self.pack()
    def __del__(self):
        try:
            #for x in self.dustbox: x.close()
            self.zf.fp.close()
        except: pass
        
if __name__ == "__main__":
        app = App();
        
        if app.initz() :
            app.open(1)
        app.mainloop()
  



[pukiwiki]

*参考ページ
-[[Cafe de Paison :http://paison.hp.infoseek.co.jp/paison/tkinter/pil1.html]]
-[[zipfile(PyMOTW):http://blog.doughellmann.com/2007/12/pymotw-zipfile.html]]
-[[zipfile — ZIP アーカイブの処理:http://www.python.jp/doc/2.4/lib/module-zipfile.html]]
-[[osモジュール 6.1.4 ファイルとディレクトリ:http://www.python.jp/doc/2.4/lib/os-file-dir.html]]
-[[Python のファイル参照や操作は面倒だというあなたに path モジュール – 傀儡師の館 – 楽天ブログ(Blog):http://b.hatena.ne.jp/entry/6592089]]~
これ使って書き直したほうがよいかも。

関連
*[[眠ってて、偶然、変なコード書いた:http://boxheadroom.com/2007/12/23/python_generator]]のは、これを作ってる時でした

[/pukiwiki]

コメントを残す

メールアドレスが公開されることはありません。