Skip to main content
 首页 » 编程设计

python之Pillow 中自动调整图片大小

2025年05月04日11txw1958

我希望给定目录中的所有图片都具有相同的大小。这就是我所拥有的:

import PIL 
import os 
import math 
 
from PIL import Image 
 
dirPath = r"C:\\a" 
dirList = os.listdir(dirPath) 
outPath = r"C:\\b" 
 
im_new = Image.new('RGB', (124,90), 'white') 
new_w = 124 
new_h = 90 
 
for (dirname, dirs, files) in os.walk(dirPath): 
    for filename in files: 
        print("Opening:"+filename) 
        thefile = os.path.join(dirname,filename) 
        im = Image.open(thefile) 
 
        old_w, old_h = im.size 
 
        x1 = int(math.floor((new_w - old_w) / 2)) 
        y1 = int(math.floor((new_h - old_h) / 2)) 
 
        im_new.paste(im, (x1, y1, x1 + old_w, y1 + old_h)) 
 
        print("Saving:"+filename) 
        outfile = os.path.join(outPath,filename) 
        im_new.save(outfile, "PNG") 
 
 
print("Done!") 

问题是,它没有正确循环。它不是将图像固定在白色背景上,而是将之前的图像放在下一个上。希望这有点道理。

请您参考如下方法:

im_new 是在循环外创建的,因此您只有一个。在循环的一次迭代中对其所做的更改在以后的迭代中是可见的。尝试在循环内创建它。

for (dirname, dirs, files) in os.walk(dirPath): 
    for filename in files: 
        im_new = Image.new('RGB', (124,90), 'white') 
        #...