Python resets image size in batches through PIL library

The original pixel size will also change the fly in the ointment

import os
from PIL import Image
import struct
import sys
#  python3 /Users/rex/Downloads/未命名文件夹/origin.py /Users/rex/Downloads/未命名文件夹

path = sys.argv[1] 
nImgW = 200
nImgH = 200
maxImgW = 0
maxImgH = 0
def list_pic(dirpath):
    for root, dirs, fs in os.walk(dirpath):
        for f in fs:
            if f.endswith('.png') or f.endswith('.jpg'):
                yield os.path.join(root, f)
 
def calcMaxWH(dirpath):
    global maxImgW,maxImgH
    for f in list_pic(dirpath):
        img = Image.open(f)
        (w,h) = img.size 
        maxImgW = max(w,maxImgW)
        maxImgH = max(h,maxImgH)


               
           
def resizeImage(dirpath):
    with open('resize_pic.output.log', 'w') as log:
        for f in list_pic(dirpath):
            img = Image.open(f)
            (w,h) = img.size
            nw = maxImgW
            nh = maxImgH
            print( (w, h),'->',(nw,nh), f)
            log.write("%s | (%d,%d)-> (%d,%d)\n"%(f,w, h,nw,nh))
            # img = img.resize((nw,nh),Image.ANTIALIAS)
            img.thumbnail((nw,nh),Image.ANTIALIAS) #只能缩小不能放大?
            print(f)
            img.show()
            img.save(f)

if '__main__' == __name__:
    calcMaxWH(path)
    resizeImage(path)

Guess you like

Origin blog.csdn.net/qq983985955/article/details/128186559