VOT Productions
VOT Productions

Reputation: 146

PNG won't autocrop using image.getbbox()

I've been trying to get thisimage I want to cropimage to automatically crop to the smallest size possible, removing the transparent bits around it. I can't just crop this image myself manually, as more things will be added on the image like this image I want to crop as well.

I've been using this code:

from PIL import Image, ImageChops

image=Image.open('headbase1.png')
image.load()

imageSize = image.size
imageBox = image.getbbox()
print(image.getbbox())
cropped=image.crop(imageBox)
cropped.save('headbase_end.png')

It does not crop out the transparency around it, and the bounding box is this (0, 0, 45, 45), which I do not think is right.

Thanks, VOT.

Edit, this does work: Automatically cropping an image with python/PIL with that image, however it refuses to work for my image. .

Upvotes: 3

Views: 2529

Answers (1)

Dean Chen
Dean Chen

Reputation: 69

getbbox doesn't work on PNGs with alpha channels: image.mode == 'RGBA'

First remove the alpha channel and then obtain the bounding box. image.convert('RGB').getbbox()

Upvotes: 4

Related Questions