0

I need to resize the the images within a folder in Python. By using the code below, how can I have the same dimension of them in the end?

from PIL import Image
import os

path = "E:/Jupyter-Project/images/test/car/"
resize_ratio = 0.5 

def resize_aspect_fit():
    dirs = os.listdir(path)
    for item in dirs:
        if item == '.jpg':
            continue
        if os.path.isfile(path+item):
            image = Image.open(path+item)
            file_path, extension = os.path.splitext(path+item)

            new_image_height = int(image.size[0] / (1/resize_ratio))
            new_image_length = int(image.size[1] / (1/resize_ratio))

            image = image.resize((new_image_height, new_image_length), Image.ANTIALIAS)
            image.save(file_path + "_small" + extension, 'JPEG', quality=90)


resize_aspect_fit()

The code works perfect, but some images are 3 K, others are 4... and I do not really know how to modify it in order to achieve the same dimension.

martineau
  • 119,623
  • 25
  • 170
  • 301
Ariadne R.
  • 452
  • 11
  • 24
  • What do you mean by "the same dimension of them"? – martineau Jan 10 '21 at 00:38
  • By this I mean that I need all of the images to be *exactly 4 KB*, for example. Instead of how it is working now - some have 3 KB in the end, some 4 KB, some 5 KB and so on .. – Ariadne R. Jan 10 '21 at 00:40
  • _Which_ dimension of them, width or height? The code you have now just makes both dimension ½ what they were originally. – martineau Jan 10 '21 at 00:42
  • both width and height – Ariadne R. Jan 10 '21 at 00:46
  • They are all square? Regardless, see [resizing all images in a folder using PIL](https://stackoverflow.com/questions/55071683/resizing-all-images-in-a-folder-using-pil) – martineau Jan 10 '21 at 00:48
  • 1
    *"By this I mean that I need all of the images to be exactly 4 KB"* Sorry, that's not going to happen with JPEG images. If you want images that are all the same file size, you need to use a file format that doesn't use compression. But then all of the files will be much bigger than the corresponding JPEG files. – user3386109 Jan 10 '21 at 02:34
  • @user3386109: The OP is talking about the dimension of image — its width and height in pixels — not file size. – martineau Jan 10 '21 at 15:22
  • @martineau How does KB ([see OP's first comment](https://stackoverflow.com/questions/65649035/how-to-resize-the-images-in-order-to-have-the-same-dimension-in-the-end?noredirect=1#comment116070491_65649035)) translate to image dimensions? – user3386109 Jan 10 '21 at 19:09
  • @user3386109: It's unclear what the OP meant and is the first thing I asked them (see very first comment). I think it's what I said and is what the "aspect" of an image usually means. The OP could / should clarify what they want so we don't have to guess. – martineau Jan 10 '21 at 20:17

0 Answers0