python批量對圖片文件進行尺寸縮小處理

# -*- coding: utf-8 -*-
"""
當前文件夾下圖片壓縮尺寸到400*225大小以內,生成到outpath下
可在虛擬環境下生成exe執行文件使用
# pip install -i https://pypi.tuna.tsinghua.edu.cn/simple Image
# pip install -i https://pypi.tuna.tsinghua.edu.cn/simple pyinstaller
# pyinstaller -F img.py
"""

from PIL import Image
import os

def cut_image(file, outpath):
    """
    圖片壓縮尺寸到400*225大小以內,生成到outpath下
    """
    img = Image.open(file)
    print(img.size)
    (image_x,image_y) = img.size
    if not (image_x <= 400 and image_y <= 225):
        if (image_x/image_y) > (400/225):
            new_image_x = 400
            new_image_y = 400 * image_y // image_x
        else:
            new_image_y = 225
            new_image_x = 225 * image_x // image_y
    else:
        new_image_x = image_x
        new_image_y = image_y
        
    new_image_size = (new_image_x,new_image_y)
    print(new_image_size)
        
    new_img = img.resize(new_image_size,Image.ANTIALIAS)
    new_img.save(outpath+file)
    


if __name__ == "__main__":
    # 當前路徑下的所有文件
    path = '.'
    files  = os.listdir(path)
    
    # 生成當以下文件夾下
    outpath = './small/'
    isExists=os.path.exists(outpath)
    if not isExists:
        os.makedirs(outpath)
  
    # 對圖片文件逐一處理
    for file in files:
        filename,filetype = os.path.splitext(file)
    #    print(filename,filetype)
        if filetype == '.jpeg' or filetype == '.jpg' or filetype == '.png':
            print(file)
            cut_image(file, outpath)
    
    # exe生成完後,控制檯暫停下
    os.system('pause')

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章