- 论坛徽章:
- 2
|
本帖最后由 大邪神 于 2012-08-21 22:22 编辑
自己写的,真的没用过Py,网上找找改改,就成了。
功能:把某个目录下的大图片缩小并按比例填充,因为我的系统一则不需要那么大的图片,二则比较老,只支持4:3的比例。
Ps:由于PIL只支持2.X,所以.....
大家看看,改进一下
-------------------------CODE-----------------------------
# -*- coding: cp936 -*-
import Image,ImageEnhance
import glob, os
# tianchong:函数中:w9, h9 指宽高比例;w, h 指实际宽高; w0, h0 指按照比例应该的宽高;pw, ph 指开始绘图的坐标;
def T_adjimg(im, wh, bg = (0xff,0xff,0xff,0xff),mode = "RGBA"):
if(im is None):
return None
w9,h9=wh
w,h= im.size
if( w9*h > h9*w ):
w0=w9*h/h9
h0=h
pw=(w0-w)/2
ph=0
else:
h0=h9*w/w9
w0=w
ph=(h0-h)/2
pw=0
nb_im = Image.new(mode,(w0,h0),bg)
nb_im.paste(im,(pw,ph))
return nb_im
# 图片缩放:
def T_sfim(im,wh = (240,320)):
if(im is None):
return None
w2,h2 = w,h = im.size
w0,h0 = wh
# if(h!>h0 )
if(h>h0):
h2 = h0
w2 = w*h0/h
return im.resize((w2, h2),Image.ANTIALIAS)
# 图片处理: 由于图片多为高比例过大,所以以高为标准,按比例调整宽。
def timage():
for files in glob.glob('F:\\KSZP-1\\*.JPG'):
filepath,filename = os.path.split(files)
filterame,exts = os.path.splitext(filename)
#输出路径
opfile = r'F:\\TT\\'
#判断opfile是否存在,不存在则创建
if (os.path.isdir(opfile)==False):
os.mkdir(opfile)
im = Image.open(files)
w,h = im.size
if(h>320):
im=T_sfim(im,(240,320))
im_nb = T_adjimg(im,(3,4))
if(not(im_nb is None)):
im_nb.save(opfile+filterame+'.jpg')
else:
print "Error Open File:"+filename
if __name__=='__main__':
timage()
print '哈哈,OK啦!'
|
|