python+imageMagick寫的一個壓縮圖片腳本

!/usr/bin/python import os import cPickle as p import re import Image def imageCompre(imagedir = '.', imagelistfile="image.data"): datafile = imagedir+'/'+imagelistfile allowImageType = ['jpg','jpeg','gif','png'] pre = re.compile('^big|^sml|^mid*'); if os.path.isfile(datafile): f = file(datafile) imagelist = p.load(f) f.close() else: imagelist = [] for item in os.listdir(imagedir): if item: if os.path.isdir(imagedir+"/"+item): imageCompre(imagedir+"/"+item,'image.data') else: if item.split('.')[-1] in allowImageType and item not in imagelist and not pre.match(item): imagelist.append(item); #convert image file convertImage(imagedir,item) #update image.data if imagelist: f = file(datafile, 'w') p.dump(imagelist, f) f.close() #delete imagelist tuple del imagelist def convertImage(imagedir,item): sourcefile = imagedir+"/"+item im = Image.open(sourcefile); if im.size[0]<=120: os.system("cp %s %s/big-%s -a" %(sourcefile,imagedir,item)) os.system("cp %s %s/mid-%s -a" %(sourcefile,imagedir,item)) os.system("cp %s %s/sml-%s -a" %(sourcefile,imagedir,item)) else: if im.size[0] > 640: os.system("convert -resize 640 %s %s/big-%s" %(sourcefile,imagedir,item)) os.system("convert -resize 400 %s %s/mid-%s" %(sourcefile,imagedir,item)) os.system("convert -resize 120 %s %s/sml-%s" %(sourcefile,imagedir,item)) elif 400 < im.size[0] <= 640: os.system("cp %s %s/big-%s -a" %(sourcefile,imagedir,item)) os.system("convert -resize 400 %s %s/mid-%s" %(sourcefile,imagedir,item)) os.system("convert -resize 120 %s %s/sml-%s" %(sourcefile,imagedir,item)) elif 120 < im.size[0] <= 400: os.system("cp %s %s/big-%s -a" %(sourcefile,imagedir,item)) os.system("cp %s %s/mid-%s -a" %(sourcefile,imagedir,item)) os.system("convert -resize 120 %s %s/sml-%s" %(sourcefile,imagedir,item)) #init image dirRoot = raw_input('input images directory (default is ./)') if len(dirRoot) == 0: dirRoot = '.' if os.path.isdir(dirRoot): imageCompre(dirRoot); else: print 'the directory %s is not exists' %dirRoot; 
相關文章
相關標籤/搜索