Skip to content

Instantly share code, notes, and snippets.

@chenzx
Created January 7, 2013 09:37
Show Gist options
  • Save chenzx/4473714 to your computer and use it in GitHub Desktop.
Save chenzx/4473714 to your computer and use it in GitHub Desktop.
Use ImageMagicK's convert.exe to batch convert image files
#!/usr/bin/env python
# encoding: utf-8
#
import os
import os.path
import sys
import time
def do_convert(from_path, to_dir, to_filename):
to_path = os.path.join(to_dir, to_filename)
print 'do_convert: from_path=%s to_path=%s' % (from_path, to_path)
os.system('.\\convert.exe %s -resize 25%% %s' % (from_path, to_path))
def is_image_file( path ):
return path.lower().endswith('.jpg') or path.lower().endswith('.png')
#当前不支持嵌套子目录
def do_batch_convert(basepath, from_reldir, to_reldir):
print 'do_batch_convert: batch convert image files from dir <%s> to <%s>' % (from_reldir, to_reldir)
from_dir = os.path.join(basepath, from_reldir)
to_dir = os.path.join(basepath, to_reldir)
paths = os.listdir( from_dir )
for path in paths:
from_path = os.path.join(from_dir, path)
if is_image_file( from_path ):
#Save to target to_dir
if not os.path.exists(to_dir):
os.mkdir(to_dir)
to_filename = path
do_convert(from_path, to_dir, to_filename)
def Main():
run_basepath = os.getcwd().replace('\\','/').lower()
if len(sys.argv)!=3:
print 'Usage: python batch_convert.py <input_dir> <output_dir>'
sys.exit(0)
else:
do_batch_convert(run_basepath, sys.argv[1], sys.argv[2])
if __name__ == '__main__':
sys.exit(Main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment