Search code examples
pythonimagepng

Crop a PNG image to its minimum size


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

NB: The border size is not a fixed value, but may vary per image.


Solution

  • PIL's getbbox is working for me

    im.getbbox() => 4-tuple or None

    Calculates the bounding box of the non-zero regions in the image. The bounding box is returned as a 4-tuple defining the left, upper, right, and lower pixel coordinate. If the image is completely empty, this method returns None.

    Code Sample that I tried, I have tested with bmp, but it should work for png too.

    import Image
    im = Image.open("test.bmp")
    im.size  # (364, 471)
    im.getbbox()  # (64, 89, 278, 267)
    im2 = im.crop(im.getbbox())
    im2.size  # (214, 178)
    im2.save("test2.bmp")