views:

219

answers:

3

I need to check the dimensions of images in a directory. Currently it has ~700 images. I just need to check the sizes, and if the size does not match a given dimension, it will be moved to a different folder. How do I get started?

+3  A: 

You can use the Python Imaging Library (aka PIL) to read the image headers and query the dimensions.

One way to approach it would be to write yourself a function that takes a filename and returns the dimensions (using PIL). Then use the os.path.walk function to traverse all the files in the directory, applying this function. Collecting the results, you can build a dictionary of mappings filename -> dimensions, then use a list comprehension (see itertools) to filter out those that do not match the required size.

gavinb
I did this but with os.listdir instead.. works pretty well with ~700 images. Is os.path.walk better?
john2x
If `os.listdir` does what you need, that's fine. The main difference is that `os.walk` will recurse into subdirectories.
gavinb
+1  A: 

One common way is to use PIL, the python imaging library to get the dimensions:

from PIL import Image
import os.path

filename = os.path.join('path', 'to', 'image', 'file')
img = Image.open(filename)
print img.size

Then you need to loop over the files in your directory, check the dimensions against your required dimensions, and move those files that do not match.

mhawke
+1  A: 

If you don't need the rest of PIL and just want image dimensions of PNG, JPEG and GIF then this small function (BSD license) does the job nicely:

http://code.google.com/p/bfg-pages/source/browse/trunk/pages/getimageinfo.py

jtes0111