python 练习0005

版权声明:喜欢就点个赞吧,有啥疑问可以留言交流~ https://blog.csdn.net/m0_38015368/article/details/89238868

问题

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

代码

from PIL import Image
import os

def get_pics(file_dir):
    try:
        os.chdir(file_dir)
        return [os.path.abspath(name) for name in os.listdir()
                if name.endswith('.jpg') or name.endswith('.png')]
    except:
        print('Dir not exits')
        return None

def process_pics(pics, max_thumbnail):
    process_num = len(pics)
    processed_num = 0
    max_width, max_height = max_thumbnail
    for pic in pics:
        image = Image.open(pic)
        width, height = image.size
        if width > max_width or height > max_height:
            rate = max(width / max_width, height / max_height)
            image.thumbnail((width / rate, height / rate))
            new_path = pic.split('.')[0] + '_new.' + pic.split('.')[1]
            image.save(new_path)
            processed_num += 1
            print(pic + ' has processed')
        else:
            print(pic + ' has not processed')

    print('------------------------------')
    print('All: ', process_num)
    print('Processed', processed_num)


if __name__ == '__main__':
    # iphone5分辨率 : (1136, 640)
    max_thumbnail = (1136, 640)
    file_dir = './pic'
    pics = get_pics(file_dir)
    # print(pics)
    process_pics(pics, max_thumbnail)

小知识

路径处理

  • os.chdir(newpath) 函数可以切换当前路径到 newpath
  • os.path.abspath(file) 函数获取 file 的绝对路径
  • os.listdir() 函数列出当前文件夹下所有文件

字符串函数

string.endswith('key')string.startswith('key') 可以判断字符串 string 是否以 key 开头或结尾。

猜你喜欢

转载自blog.csdn.net/m0_38015368/article/details/89238868
今日推荐