Resizing Image Files with Python

Yesterday I came back from my holidays in Korea with a whole bunch of pictures which I now want to upload to my website to share them with my friends. Usually I take high resolution pictures with a size of 3056×1334 pixel. That’s of course to big for publishing them in the internet, so I wrote a small python script to convert them to 800×600 automatically by using the Unix convert command:

#!/usr/bin/env python
  1. -*- coding: utf-8 -*-
import sys import commands def convert(file, resize="800x600", prefix="small"): try: cmd = "convert -resize " + resize + " " + file + " " + prefix + "_" + file commands.getstatusoutput(cmd) except e: print e def usage(prog): print "Usage:", prog, "-r RESIZE -p PREFIX FILES..." if __name__ == "__main__": argv = sys.argv[1:] if len(argv) <= 1: usage(sys.argv[0]) sys.exit(-1) resize = "800x600" prefix = "small" for i in range(len(argv)): arg = argv[i] if arg == "-r" and i+1 < len(argv): resize = argv[i+1] elif arg == "-p" and i+1 < len(argv): prefix = argv[i+1] elif argv[i-1] != "-r" or argv[i-1] != "-p": convert(arg, resize, prefix)

Run the script with convert.py *.jpg and it will convert all jpg file into 800×600 pixel images while preserving the original file and creating new ones named “small_ORIGINALFILENAME”. Use the parameters “-r” and “-p” to define the resize rate or to change the prefix, see man convert for more details.

Advertisements

0 Responses to “Resizing Image Files with Python”



  1. Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s





%d bloggers like this: