Home > front end >  Checking a folder for an image that matches certain requirements
Checking a folder for an image that matches certain requirements

Time:03-25

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.

CodePudding user response:

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)

CodePudding user response:

import os
from PIL import Image

img_dir = 'images/'

img_width = 350
img_height = 400

for image in os.listdir(img_dir):
    img = Image.open(img_dir   image)
    width = img.width
    height = img.height

    if width == img_width and height == img_height:
        print(img_dir   image   " height: ", height)
        print(img_dir   image   " width: ", width)
  • Related