python中等比例缩图像
import os
from PIL import Image
ext = ['jpg','jpeg','png']
files = os.listdir('.')
def process_image(filename, mwidth=200, mheight=400):
image = Image.open(filename)
w,h = image.size
if w<=mwidth and h<=mheight:
print(filename,'is OK.')
return
if (1.0*w/mwidth) > (1.0*h/mheight):
scale = 1.0*w/mwidth
new_im = image.resize((int(w/scale), int(h/scale)), Image.ANTIALIAS)
else:
scale = 1.0*h/mheight
new_im = image.resize((int(w/scale),int(h/scale)), Image.ANTIALIAS)
new_im.save('new-'+filename)
new_im.close()
for file in files:
if file.split('.')[-1] in ext:
process_image(file)
这段代码展示了如何使用Python的PIL库批量处理图片,将大于指定尺寸的图像等比例缩放,以适应特定的宽度和高度限制,并保存为新的文件。程序首先列出指定目录下的所有文件,然后检查文件是否为jpg、jpeg或png格式,如果是,则调用process_image函数进行处理。
193

被折叠的 条评论
为什么被折叠?



