Search code examples
pythonpython-3.ximageinfinite-loopimage-resizing

Infinite loop when resizing images


I am running my code to resize all images in a directory however the code goes on an infinite loop. The images are resized how I want I just can not figure out how to make it stop after one pass. Also I would like to specify the output to be a .jpg file type.

import os, sys
from PIL import Image
import glob as glob

MY_DIRECTORY = "C:\\Users\\rzara\\Desktop\\sample_skulls"
for root, subdirs, files in os.walk(MY_DIRECTORY):
    for filename in files:
        for filename in glob.glob(MY_DIRECTORY+"/*.jpg"):
            size = 250, 250
            file_parts = os.path.splitext(filename)
            outfile = file_parts[0] + '_250x250' + file_parts[1]
            try:
                img = Image.open(filename)
                img = img.resize(size, Image.ANTIALIAS)
                img.save(outfile)
            except IOError as e:
                print("An exception occured '%s'" %e)

I tried changing the save line to:

img.save(outfile,'jpg')

but that gives and error of:

line 1983, in save 
save_handler = SAVE[format.upper()]
KeyError: 'JPG'

Solution

  • I see two problems.

    First, you are calling walk and glob, and iterating over the results of both. That means if your directory contains five files and all of them satisfy glob's pattern, you will iterate over five files five times for a total of twenty five times. You should only have one for filename loop.

    Second, "jpg" does not appear to be a supported PIL file format. However, "JPEG" is. Try that instead. (Yes, I find it strange that img.save("result.jpg") understands that the result should be a jpeg, but img.save("result", "jpg") doesn't. Sometimes libraries are weird.)

    All together, the result might look like:

    import os, sys
    from PIL import Image
    import glob as glob
    
    MY_DIRECTORY = "C:\\Users\\rzara\\Desktop\\sample_skulls"
    for filename in glob.glob(MY_DIRECTORY+"/*.jpg"):
        size = 250, 250
        file_parts = os.path.splitext(filename)
        outfile = file_parts[0] + '_250x250' + file_parts[1]
        img = Image.open(filename)
        img = img.resize(size, Image.ANTIALIAS)
        img.save(outfile, 'jpeg')