第 0005 题:你有一个目录,装了很多照片,把它们的尺寸变成都不大于 iPhone5 分辨率的大小。
from PIL import Image
import os
IPHONE_5 = (1136, 640)
PIC_DIR = '/home/hqi/source_code/python/show_me_the_code'
def change_resolution(pic_path, resolution):
img = Image.open(pic_path)
x, y = img.size
factor_x = float(x) / resolution[0]
factor_y = float(y) / resolution[1]
new_x = x if factor_x < 1 else resolution[0]
new_y = y if factor_y < 1 else resolution[1]
img.resize((new_x, new_y)).save('change_'+pic_path)
def filter_pic(_dir):
files = os.listdir(_dir)
for file in files:
if file.endswith('.jpg'):
change_resolution(file, IPHONE_5)
if __name__ == '__main__':
#change_resolution('pet.jpg', IPHONE_5)
filter_pic(PIC_DIR)