!/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;
因为工作学要,写的有些着急了,难免有不合理的地方,希望大家多多拍砖。
主要是使用 python + imageMagick 对用户上传的图片进行压缩。