2022년 10월 20일 목요일

[python] Directory / Zip to Resize

from fpdf import FPDF
from PIL import Image
import zipfile
import sys
import os
import io

a4_w = 595.28
a4_h = 841.89
max_img_h = a4_h * 4
max_page_h = a4_h * 12

def key_str_num(path):
    import re
    strList = re.split('(\d+)',path)
    strList = [x for x in strList if len(x) > 0]
    newStr = []
    for s in strList:
        try: newStr += "%04d" % int(s)
        except: newStr += s          
    return newStr

def dir2dir(src_dir,dest_dir,width=None):
    def get_listdir(folder):
        file_list = []
        files = os.listdir(folder)
        for file in files:
            path = os.path.join( folder, file )
            if os.path.isdir(path): file_list += get_listdir(path)
            else: file_list.append(path)
        return file_list
    def write_file(path,data):
        with open(path,"rw") as f:
            f.write(data)
    src_dir = os.path.normpath(src_dir)
    dest_dir = os.path.normpath(dest_dir)
    if not os.path.exists(dest_dir): os.mkdir(dest_dir)
    error = []
    namelist = get_listdir(src_dir)
    namelist = sorted(namelist, key=key_str_num)
    for name in namelist:
        if os.path.isdir(name): continue
        try:
            image = Image.open(name)
            if width and image.width > width:
                image = image.resize((width,int(width*image.height/image.width)), Image.ANTIALIAS)
            filename = os.path.join(dest_dir, name[len(src_dir)+1:])
            dirname = os.path.dirname(filename)
            if not os.path.exists(dirname): os.mkdir(dirname)
            image.save( filename, quality=70 )
            print(filename)
        except Exception as e:
            error.append((name,e))
    for e in error: print(e)    
    
def zip2zip(src,dest,width=None):
    def is_dir(filename):
        return filename.endswith('/') or filename.endswith('\\')
    error = []
    in_zip = zipfile.ZipFile(src)
    out_zip = zipfile.ZipFile(dest, mode='w')
    namelist = in_zip.namelist() #filename
    namelist = sorted(namelist, key=key_str_num)
    for name in namelist:
        if is_dir(name): continue
        image_bytes = in_zip.read(name)
        try:
            image = Image.open(io.BytesIO(image_bytes))
            if width and image.width > width:
                image = image.resize((width,int(width*image.height/image.width)), Image.ANTIALIAS)
            image_bytes = io.BytesIO()
            image.save(image_bytes, format='jpeg', quality=70)
            #image_bytes.seek(0) + image_bytes.read() -> getvalue() or getBuffer().tobytes()
            name = name.encode('cp437').decode('euc-kr','ignore')
            out_zip.writestr(name, image_bytes.getvalue(), compress_type=zipfile.ZIP_DEFLATED, compresslevel=9)
            print(name)
        except Exception as e:
            error.append((name,e))
    out_zip.close()
    for e in error: print(e)

def img2img(src,width=None):
    if os.path.isdir(src):
        dir2dir(src,src + ".zip",width)
    else:
        if zipfile.is_zipfile(src):
            zip2zip(src,src + ".zip",width)
        else:
            print( src, 'is neigher direcotry nor zipfile')
            
def show_gui():
    def file_drop(files):
        global file_list
        file_list = []
        for file in files:
            table.Add( (os.path.basename(file), "Ready") )
            file_list.append(file)  
    def make_handler(ev):
        for file in file_list:
            img2img(file)
        print(file_list)
    def get_panel(parent):
        global table
        panel = w.VBox(parent)
        table = w.Table(panel, ( ('File', 500, -1), ('Status', 70, 0) ), drop=file_drop)
        button = w.Button(panel, "Make", make_handler )
        panel.Add( table, expand=True, fill=True )
        panel.Add( button, expand=False, fill=False, right=True )
        return panel
    import wxez as w
    win = w.WxWin("Image to PDF", 600, 400)
    panel = get_panel(win)
    win.Add(panel, expand=True, fill=True)
    win.Run()
    
if __name__ == "__main__":
    if len(sys.argv) < 3:
        show_gui()
    elif len(sys.argv) == 2:
        img2img(sys.argv[1])
    elif len(sys.argv) == 3:
        img2img(sys.argv[1],int(sys.argv[2]))

댓글 없음:

댓글 쓰기