Home > Software design >  Python add padding to images that need it
Python add padding to images that need it

Time:10-27

I have a bunch of images that aren't equal size, and where some fit entirely to the frame and some have blank padding.

I would like to know how I can resize each of them to be the same image size and to have roughly the same border size.

Currently I am doing

from PIL import Image
from glob import glob

images = glob('src/assets/emotes/medals/**/*.png', recursive=True)

for image_path in images:
    im = Image.open(image_path).convert('RGBA')
    im = im.resize((100, 100))
    im.save(image_path)

but this doesn't account for a possible border.

Image 1 - 101 x 101
image 1 w/ border image 1

Image 2 - 132 x 160
image 2 w/ border image 2

Desired result - 100 x 100
desired 1 w/ border desired 1

desired 2 w/ border desired 2

Images arent always bigger than (100, 100) so I will need to use resize.

I can also maybe remove the PNG border for all images, and then resize which might be easier.

CodePudding user response:

Taken from Crop a PNG image to its minimum size, im.getbbox() will give you the original image without transparent background.

Documentation : Pillow (PIL Fork)

  • Related