Crop an image in the centre using PIL

后端 未结 7 1392
闹比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:24

    I originally used the accepted answer:

    import Image
    im = Image.open()
    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))
    

    But I came into the problem mentioned by Dean Pospisil

    One potential problem with the proposed solution is in the case there is an odd difference between the desired size, and old size. You can't have a half pixel on each side. One has to choose a side to put an extra pixel on.

    Dean Pospisil's solution works, I also came up with my own calculation to fix this:

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

    With the accepted answer, an image of 180px x 180px to be cropped to 180px x 101px will result in a cropped image to 180px x 102px.

    With my calculation, it will be correctly cropped to 180px x 101px

提交回复
热议问题