Crop an image in the centre using PIL

后端 未结 7 1234
闹比i
闹比i 2021-01-31 03:41

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 co

相关标签:
7条回答
  • 2021-01-31 04:31

    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).

    0 讨论(0)
提交回复
热议问题