Hello, please sign in or register
You are here: Home

Batch image resizing using Python

Loop through files in a directory. According to the type gather information about the dimensions. Scale images to a new size.

 

#! /usr/bin/env python

# resize an image using the PIL image library
# free from:  http://www.pythonware.com/products/pil/index.htm
# tested with Python24        vegaseat     11oct2005

import Image
from decimal import Decimal, getcontext
import struct
import os


def jpegsize(path):
	stream = open(path, "rb")
	(x, y, error) = (None, None, "could not determine JPEG size")
	# Dummy read to skip header ID
	stream.read(2)
	while True:
		# Extract the segment header.
		(marker, code, length) = struct.unpack("!BBH", stream.read(4))

		# Verify that it's a valid segment.
		if marker != 0xFF:
			# Was it there?
			error = "JPEG marker not found"
			break
		elif code >= 0xC0 and code <= 0xC3:
			# Segments that contain size info
			(y, x) = struct.unpack("!xHH", stream.read(5))
			error = "no error"
			break
		else:
			# Dummy read to skip over data
			stream.read(length - 2)

	return ("JPEG", x, y, error)




# Walk a directory and create the resize the image files in there.
path = 'C:\Documents and Settings\user\My Documents\My Pictures'

for x in os.listdir(path):
	base = x
	x = path + '\\' + x

	if os.path.isdir(x) == True:
		print "Skipping directory " + x
		continue

	(imgtype, imgx, imgy, error) = jpegsize(x)
	print imgx
	if imgx == None:
		print "this is not a jpeg"
		continue

	print imgx, imgy, Decimal(imgx)/Decimal(imgy)
        
	# What is the image ratio, we need this to help resize
	iratio = Decimal(imgx)/Decimal(imgy)

	# adjust width and height to your needs
	mwidth = 1000
	mheight = mwidth
	mratio = Decimal(mwidth)/Decimal(mheight)

	# which one to use the x or the y value... if current image dimensions are wider or taller than the limits 

	if iratio >= mratio:
	    #the original image is wider than the limiting area, so we scale according to the x axis
	    width = mwidth
	    height = int( width / iratio ) 
	elif iratio < mratio:
	    #the original image is taller than the limiting area, so we scale according to the y axis
	    height = mheight 
	    width = int( height * iratio )

	print width, height

	im1 = Image.open(x)
	im2 = im1.resize((width, height), Image.NEAREST)      # use nearest neighbour
	ext = ".jpg"
	im2.save("compact/" + base)


print "COMPLETE"

Comments

burberry outlet
If you know the other person is satisfied as hot-tempered type of this group of customers, everything you may have to carefully, it is best not to commit any errors.
Created 05/05/12
Tory Burch Outlet
Westminster-born Karena is intrigued by Tory Burch Outlet electronics, frisbee golf - frolf. Almost all her motivation originates from exploring and making your way to different locations and countries ...
Created 08/05/12
Nike Shox Cheap
Senior manager sem Gunne is interested in [url=http://www.nike--outlet.com/]Nike Air Max[/url] rc planes and physical exercise (aerobics weights). And finally, the things she treasure most is following an colorado avalanche icehockey match live.
Created 09/05/12
Nike Shox Cheap
Senior manager sem Gunne is interested in [url=http://www.nike--outlet.com/]Nike Air Max[/url] rc planes and physical exercise (aerobics weights). And finally, the things she treasure most is following an colorado avalanche icehockey match live.
Created 09/05/12
nike free
Senior Web designer Zeynep hobbies and interests include nike free, tai-chi, fishing. Last of all she's interested in discovering new towns and cities to give an example Agana, Guam.
Created 12/05/12
nike air max online
Omaha-born Rosenda is definitely hooked on nike shoes, swimming Nike Air Max, building dollhouses. And lastly the things she appreciate among the most is exploring and making your way to different places and...
Created 13/05/12
nike air max
Bartender Rosenda Czach is truly hooked on Nike Air Max nike air max, electro-rock, textiles. Last but not least she's empowered by discovering new places as an example, to Hanoi.
Created 13/05/12
tory burch flats
Atlantic City-born Jame is without a doubt addicted to http://tory-burch--flats.com/ tory burch outlet .http://www.nikefreerun-30.com/ nike free 3.0 electronics market, jewelry making. Finally, she gets stimulated by loosening up together with her fr...
Created 24/05/12
tory burch flats
Atlantic City-born Jame is without a doubt addicted to http://tory-burch--flats.com/ tory burch outlet .http://www.nikefreerun-30.com/ nike free 3.0 electronics market, jewelry making. Finally, she gets stimulated by loosening up together with her fr...
Created 24/05/12
nike free run
thanks for the great post. it reminds me that i have to bring more structure into my blogging. your blog is very interesting. http://www.nikefreerunairmax.info
Created 09/08/12
Adidas F50 Adizero
really impressed! everything is very open and very clear explanation of issues. it contains truly information. your website is very useful. thanks for sharing. looking forward to more!
Created 26/09/12
Jang Jobs Ads
I recently came across your blog and have been reading along. I thought I would leave my first comment. I don’t know what to say except that I have enjoyed reading. Nice blog. I will keep visiting this blog very often.
Created 20/09/13
purchase Modafinil
Really impressed ! Everything is very open and very clear explanation of issues. It contains truly information. Your website is very useful.purchase Modafinil
Created 15/05/14
purchase Modafinil
Really impressed ! Everything is very open and very clear explanation of issues. It contains truly information. Your website is very useful. [url=http://www.worldpharmcare.com/buy-modafinil-online-200mg]purchase Modafinil[/url]
Created 15/05/14
Buy Modanifil 200mg
really impressed with this blog. Will definitely help people reading this....
Created 14/11/14
Title*
Comment

Prove you are not a robot

To prove you are not a robot, please type in the six character code you see in the picture below
Security confirmation codeI can't see this!
Contact
Name*
Email never shown*
Home Page

Author

Andrew Dodson
Since:Feb 2007

Comment | flag

Categories

Bookmark and Share