Show me the code_0005题

0005题:你有一个目录,装了很多照片,把它们的尺寸变成都不大于iPhone5分辨率的大小。

iPhone5采用4英寸视网膜屏,屏幕分辨率为1136x640*

还是使用PIL库来解决这个问题,有个resize的方法可以改变图片的大小。

代码如下:

#! /usr/bin/env python
#coding=utf-8
import os
from PIL import Image

iPhone_WIDTH = 1136
iPhone_HEIGHT = 640

def resize_pic(path, new_path, width=iPhone_WIDTH, height = iPhone_HEIGHT):
    im = Image.open(path)
    w, h = im.size
    
    if w > width:
        h = width*h//w
        w = width
    if h > height:
        w = height * w //h
        h = height
        
    im_resized = im.resize((w, h), Image.ANTIALIAS)
    im_resized.save(new_path)
    
def walk_dir_and_resize(path):
    for root, dirs, files in os.walk(path):
        for f_name in files:
            if f_name.lower().endswith('jpg'):
                path_dst = os.path.join(root, f_name)
                f_new_name = 'iPhone5_' + f_name
                resize_pic(path=path_dst, new_path=f_new_name)
                
if __name__ == '__main__':
    walk_dir_and_resize('./')

你可能感兴趣的:(Show me the code_0005题)