views:

551

answers:

4

I want to crop a thumbnail image in my Django application, so that I get a quadratic image that shows the center of the image. This is not very hard, I agree.

I have already written some code that does exactly this, but somehow it lacks a certain ... elegance. I don't want to play code golf, but there must be a way to express this shorter and more pythonic, I think.

x = y = 200 # intended size
image = Image.open(filename)
width = image.size[0]
height = image.size[1]
if (width > height):
    crop_box = ( ((width - height)/2), 0, ((width - height)/2)+height, height )
    image = image.crop(crop_box)
elif (height > width):
    crop_box = ( 0, ((height - width)/2), width, ((height - width)/2)+width )
    image = image.crop(crop_box)
image.thumbnail([x, y], Image.ANTIALIAS)

Do you have any ideas, SO?

edit: explained x, y

+1  A: 
width, height = image.size
if width > height:
    crop_box = # something 1
else:
    crop_box = # something 2
image = image.crop(crop_box)
image.thumbnail([x, x], Image.ANTIALIAS)   # explicitly show "square" thumbnail
SilentGhost
+6  A: 

The fit() function in the PIL ImageOps module does what you want:

ImageOps.fit(image, (min(*image.size),) * 2, Image.ANTIALIAS, 0, (.5, .5))
Steef
Hmm.. this doesn't really seem to produce square images. Or am I missing something?
winsmith
The fit() function returns a new image object, I forgot to mention that. Maybe it's that?
Steef
This solved my problem exactly.
Antti Rasinen
+6  A: 

I think this should do.

size = min(image.Size)

originX = image.Size[0] / 2 - size / 2
originY = image.Size[1] / 2 - size / 2

cropBox = (originX, originY, originX + size, originY + size)
Daniel Brückner
I like having width and height variables explicitly named. Otherwise someone reading this code has to find the documentation for Image.Size
Triptych
May be there are image.Width and image.Height properties, but I don't know. I just inferred the code from the qustion.
Daniel Brückner
A: 

I want to a content analysis of a jepg image. I wish to take a jpeg imafe say 251 x 261 and pass it through an algorithm to crop it to say 96 x 87. Can this program do that like t write an intelligent cropping algorithm, with a prompt to rezie the image.