Thom Nichols

Thom

Technology is evolution outside the gene pool

Batch Photo Thumbnail Creation for FancyBox

A quick script I wrote to batch create photo thumbnails for use with FancyBox.  This means each thumbnail gets the same filename with '_m' appended before the extension.  It uses the ImageMagick command-line tool convert to perform the actual image processing.

#!/usr/bin/env python

import sys, os, subprocess


def convert(directory=None, size='300x300'):

 if not directory: directory = os.getcwd()
 print('Dir: %s' % directory)

 if not size: size='300x300'

 for f in os.listdir(directory):
  parts = f.split('.')
  if len(parts) < 2:
   print('Ignoring file %s' % f)
   continue

  name = parts[0]
  ext = parts[-1]

  if ext.lower() not in ['png','jpg','jpeg']:
   print("Ignoring non-image file %s" % f)
   continue

  outname = os.path.join(directory, "%s_m.%s" % (name,ext) )
#  with open(outname,'w') as outfile:
  cmd = [ 'convert',
    os.path.join(directory,f),
    '-resize', size+">",
    outname ]
  subprocess.call(cmd)
  print( "Resized to %s" % outname )
  

def main(args):
 directory = None
 size = None
 if len(args) > 1: directory=args[1]
 if len(args) > 2: size = args[2]

 convert(directory, size)
 return 0

if __name__ == '__main__':
 sys.exit(main(sys.argv))

Category: graphics Python