Skip to content

Instantly share code, notes, and snippets.

@physacco
Created March 2, 2015 18:10
Show Gist options
  • Save physacco/cc2a18a33a856f5aa3d2 to your computer and use it in GitHub Desktop.
Save physacco/cc2a18a33a856f5aa3d2 to your computer and use it in GitHub Desktop.
Search in current directory for image files that is smaller than specified resolution and optionally remove them.
import os
import re
import sys
import optparse
from PIL import Image
IMAGE_EXT_PATTERN = re.compile(r'\.(jpe?g|png|gif|bmp)', re.IGNORECASE)
def safe_int(string):
try:
return int(string)
except Exception:
return 0
def parse_resolution(resolution):
"""Parse string WIDTHxHEIGHT into (width, height)"""
if not resolution:
return (0, 0)
parts = resolution.split('x')
if len(parts) != 2:
raise ValueError('invalid resolution format')
width = safe_int(parts[0])
height = safe_int(parts[1])
if width < 0 or height < 0:
raise ValueError('resolution cannot be negative')
return (width, height)
def find_image_files():
"""Find image files in this directory by extensions"""
names = []
for name in os.listdir('.'):
if not os.path.isfile(name):
continue
ext = os.path.splitext(name)[1]
if not re.match(IMAGE_EXT_PATTERN, ext):
continue
names.append(name)
return names
def get_image_resolution(name):
"""Open an image file and return its resolution"""
try:
image = Image.open(name)
return image.size
except Exception:
return None
def remove_file(name):
"""Try removing a file from disk"""
try:
os.unlink(name)
except Exception, e:
sys.stderr.write('Error: %s: %r\n' % (name, e))
def main():
parser = optparse.OptionParser(version='%prog 0.1.0')
parser.add_option('-R', '--resolution', dest='resolution',
help='Specify pixel resolution as WIDTHxHEIGHT')
parser.add_option('-D', '--delete', action='store_true', dest='is_delete',
help='Delete images smaller than WIDTHxHEIGHT')
(options, args) = parser.parse_args()
resolution = parse_resolution(options.resolution)
is_delete = options.is_delete
for name in find_image_files():
image_size = get_image_resolution(name)
if not image_size: # bad image file
continue
width, height = image_size
if (resolution[0] and width > resolution[0]) or \
(resolution[1] and height > resolution[1]):
continue
print '%s: %dx%d' % (name, width, height)
if is_delete:
remove_file(name)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment