2

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. .

Community
  • 1
  • 1
VOT Productions
  • 136
  • 1
  • 9

1 Answers1

3

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()

Dean Chen
  • 59
  • 3