python 대량 이미지 파일 크기 축소 처리

1641 단어 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')

좋은 웹페이지 즐겨찾기