Code Snippet: Resize Images

I'm going to be posting little bits of code here and there that I think are useful. Recently, for this blog I wanted to resize a bunch of images from the 6MP that my camera puts out (3000x2000) into something more appropriate for web publishing, say 640x480.

My current programming language that I use is Python, which is useful for a whole bunch of stuff and is what I program all my robots in.

The script resizes all the images to be 480 wide and otherwise to keep the previous aspect ratio - we don't want to distort the images if they are in Portrait (taller than wide) format. If you want a differnt size just change the "480" to something else (say "600" to get all the pictures to be around 800x600). You can also perform a format change using this technique by changing the line
newPic = "sm-"+newPic +".jpg"

To be something else, for example PNG format

newPic = "sm-"+newPic +".png"

This Python script is dependent on PIL (Python Imaging Library) and the Win32 libraries and is written using Python 2.5 but should work in later versions:

Python for Windows
PIL Python Imaging Library
WIN32 for Python Utilities

Here goes:

import Image
import os

ddd = os.listdir(".")
pics = []
for ent in ddd:
if ent.find("jpg")>0:
print len(pics)

for pic in pics:
im = Image.open(pic)
print "OPEN: ",pic
imSize = im.size
print "Old Size:",imSize
imSize = (imSize[0]*480/imSize[1], 480)

im2 = im.resize(imSize,Image.ANTIALIAS)
print "New Size:",imSize
ns = len(pic)
ns -=4 #take off suffix
newPic = pic[:ns]
newPic = "sm-"+newPic +".jpg"
print "SAVED: ",newPic
print " "

print "FINISHED"
## end

NOTE The blogger software is removing all of the tabs and formats from this code. If you know python you know it works by indenting loops

You can find another person's code for this at this location

Resize Image Code

No comments:

Post a Comment

Please refrain from offensive language. Creative substitutes are encouraged.