Search code examples
pythonpython-3.xdirectorypython-imaging-library

Checking a folder for an image that matches certain requirements


I have a folder that has about 5 images in and I want to search through the folder and see if any images fit the criteria I am looking for (e.g. 350 width 400 height). I am not sure where to start or what modules I need for this I don't image any, my code can be seen below to see the format the width and height are stored in.

image1 = str(input("Please enter the image filename: "))
open_img1 = Image.open(image1)
w, h = open_img1.size

Any solution or advice would be helpful.


Solution

  • You need to import pillow (pip install pillow to install the library but import PIL to use it in your code) and then you will have something like that:

    import os
    import PIL.Image
    
    for filename in os.listdir():
        if filename.split(".")[-1] in ["png", "jpeg"]:
            image = PIL.Image.open(filename)
            if image.size == (350, 400):
                print(filename)