Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Crop a PNG image to its minimum size

Tags:

python

image

png

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

like image 984
jack Avatar asked Dec 15 '09 05:12

jack


1 Answers

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")
like image 50
YOU Avatar answered Sep 21 '22 17:09

YOU