Crop an image in the centre using PIL

后端 未结 7 1384
闹比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:16

    May be i am late to this party but at least i am here I want to center crop the image convert 9:16 image to 16:9 portrait to landscape

    This is the algo i used :

    1. divide image in 4 equal parts
    2. discard part 1 and part four
    3. Set left to 0, right to width of image

    code :

    from PIL import Image
    
    im = Image.open('main.jpg')
    width, height = im.size
    
    if height > width:
        h2 = height/2
        h4 = h2/2
    
        border = (0, h4, width, h4*3)
    
        cropped_img = im.crop(border)
        cropped_img.save("test.jpg")
    

    before :

    after:

    I hope this helps

提交回复
热议问题