3

I want to resize my images to the following ratios :rescale images in the range x0.5, x0.75, x0.9, x1.1 x1.25, x1.5 basically all i want to give as input is let's say 0.5 and all the images in my folder will have their sizes in half . Note that my images have different sizes and yes i know how to get the height and width of an image and multiply it by an input and yes i have checked this previous question on here How do I resize an image using PIL and maintain its aspect ratio? but is there a better way to do it since then?

Edit: Is something like this possible:

import os
from PIL import Image
path = path_to_input_images
for filename in os.listdir(path + 'image/'):
    im = Image.open(path + 'image/' + filename)
    im.size = list(im.size)
    im.size[0] = int(float(im.size[0]) * 0.5)
    im.size[1] = int(float(im.size[1]) * 0.5)
    im.size = tuple(im.size)
    im.save(path + 'resized_images'+ filename)

but i got an error that ValueError: tile cannot extend outside image

Allen
  • 149
  • 2
  • 12
  • I don't think there is an easier way. Just put the code in a utility function and you are all set. If you want to hide the clutter of the utility function, place it in a separate module and import it into your main program. – unutbu Feb 20 '18 at 15:28
  • @unutbu kindly feel free to share the code in answers or adjust mine in the edit section if possible. – Allen Feb 20 '18 at 15:39

1 Answers1

2

I don't think there is an easier way. Just put the code in a utility function and you are all set.

import os
from PIL import Image


def rescale(im, ratio):
    size = [int(x*ratio) for x in im.size]
    im = im.resize(size, Image.ANTIALIAS)
    return im

def process_dir(path):
    image_dir = os.path.join(path, 'image')
    for filename in os.listdir(image_dir):
        filepath = os.path.join(image_dir, filename)
        im = Image.open(filepath)
        im = rescale(im, 0.5)
        im.save(path_to_output)

process_dir(path_to_input_images)

I wasn't able to reproduce the ValueError you are seeing, but I can produce a SystemError:

SystemError: tile cannot extend outside image

by expanding im.size and then attempting to save it to a new file:

In [78]: im = Image.open(FILENAME)
In [79]: im.size
Out[79]: (250, 250)
In [82]: im.size = (500, 500)
In [83]: im.save('/tmp/out.png')
SystemError: tile cannot extend outside image

Do not try to reassign im.size. To rescale the image, call im.thumbnail or im.resize. Since you may want to rescale the image by a ratio > 1, im.resize is the right method to use here.

unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677