Question

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

Was it helpful?

Solution

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)

OTHER TIPS

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

ImageOps.fit(image, (min(*image.size),) * 2, Image.ANTIALIAS, 0, (.5, .5))
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

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top