第4题:有一个目录,装了很多照片,把它们的尺寸变成都不大于 iPhone5 分辨率的大小。
#!/usr/bin/env python3
# -*- coding : utf-8 -*-
from PIL import Image
import os
def changeimgResolution(dirpath):
for filename in os.listdir(dirpath):
imgpath = os.path.join(dirpath,filename)
with Image.open(imgpath) as im:
width,height = im.size
if width > 640 or height > 1136:
wh = width / 640 if(width / 640) >= (height / 1136) else height / 1136
out = im.resize((int(width / wh),int(height / wh)))
#im.save(imgpath)
out.save(os.path.join(dirpath,'ok_' + filename.split('.')[0] + '.jpg'),'jpeg')
print('Successfully resized %s.' % imgpath)
if __name__ == '__main__':
dirpath = input('Please input dirpath:')
changeimgResolution(dirpath)