pythonpython-imaging-librarycrop

Crop an image in the centre using PIL


How can I crop an image in the center? Because I know that the box is a 4-tuple defining the left, upper, right, and lower pixel coordinate but I don't know how to get these coordinates so it crops in the center.


Solution

  • Assuming you know the size you would like to crop to (new_width X new_height):

    import Image
    im = Image.open(<your image>)
    width, height = im.size   # Get dimensions
    
    left = (width - new_width)/2
    top = (height - new_height)/2
    right = (width + new_width)/2
    bottom = (height + new_height)/2
    
    # Crop the center of the image
    im = im.crop((left, top, right, bottom))
    

    This will break if you attempt to crop a small image larger, but I'm going to assume you won't be trying that (Or that you can catch that case and not crop the image).