Crop a PNG image to its minimum size

前端 未结 6 852
旧巷少年郎
旧巷少年郎 2020-12-16 00:00

How to cut off the blank border area of a PNG image and shrink it to its minimum size using Python?

6条回答
  •  忘掉有多难
    2020-12-16 00:53

    I think it's necessary to supplement @Frank Krueger's answer. He makes a good point, but it doesn't include how to properly crop extra border color out of an image. I found that here. Specifically, I found this useful:

    from PIL import Image, ImageChops
    
    def trim(im):
        bg = Image.new(im.mode, im.size, im.getpixel((0,0)))
        diff = ImageChops.difference(im, bg)
        diff = ImageChops.add(diff, diff, 2.0, -100)
        bbox = diff.getbbox()
        if bbox:
            return im.crop(bbox)
    
    im = Image.open("bord3.jpg")
    im = trim(im)
    im.show()
    

提交回复
热议问题