Download raw (1.9 KB)
#!/usr/bin/env python # -*- coding: utf-8 -*- import os, os.path, argparse, csv from PIL import Image image_exts = ['jpg', 'jpeg', 'png', 'gif', 'tiff', 'bmp'] mm_per_inch = 25.4 resolutions = [300, 150, 120, 90] def image_mm_size(pixels, resolution): return (pixels / float(resolution)) * mm_per_inch def image_size (filepath): im = Image.open(filepath) return im.size def is_image(path): root, ext = os.path.splitext(path) return ext.lower()[1:] in image_exts def handle_image (filepath): width, height = image_size(filepath) row = { 'name': os.path.split(filepath)[1], 'size (pixels)': '{0} x {1}'.format(width, height), } for res in resolutions: row['size ({0} dpi)'.format(res)] = '{0:.2f} x {1:.2f}'.format(image_mm_size(width, res), image_mm_size(height, res)) return row def handle_dir(path): images = [] for filename in os.listdir(path): filepath = os.path.join(path, filename) if os.path.isdir(filepath): images.extend(handle_dir(filepath)) elif is_image(filepath): images.append(handle_image(filepath)) return images if __name__ == '__main__': parser = argparse.ArgumentParser(description='List images in provided path (and subfolders)') parser.add_argument('path', help='The path to list') parser.add_argument('-o', '--output', dest='output', help='The destination CSV file', default='images.csv') args = parser.parse_args() with open(args.output, 'w') as csvfile: fieldnames = ['name', 'size (pixels)'] + [ 'size ({0} dpi)'.format(res) for res in resolutions ] + [ 'license', 'source' ] writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writeheader() for row in handle_dir(args.path): writer.writerow(row)