Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's a more elegant rephrasing of this cropping algorithm? (in Python)

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

like image 741
winsmith Avatar asked Dec 05 '22 06:12

winsmith


1 Answers

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)
like image 103
Daniel Brückner Avatar answered Dec 10 '22 09:12

Daniel Brückner