Reputation: 23
I want all the pictures in given directory to have the same size. This is what I have:
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!")
The things is, it doesn't loop correctly. Rather than having an image fixed on a white background, it just throws previous ones on the next. Hope that kinda makes sense.
Upvotes: 2
Views: 97
Reputation: 76184
im_new
is created outside the loop, so you only ever have one. Changes made to it in one iteration of the loop are visible in later iterations. Try creating it inside the loop instead.
for (dirname, dirs, files) in os.walk(dirPath):
for filename in files:
im_new = Image.new('RGB', (124,90), 'white')
#...
Upvotes: 1