In this tutorial, we will use an example to show you how to add padding for an image using Image.paste().
1.Open an image using python pillow
from PIL import Image im = Image.open('data/src/astronaut_rect.bmp')
2.How to add a padding for an image?
In order to add a padding for an image, we should create a new image with a background color, then we put original image on it.
Here is an example:
result = Image.new(pil_img.mode, (width, width), background_color) result.paste(pil_img, (0, (width - height) // 2))
In this code, we will create a new image result, then put original image pil_img on it.
We will create a function to add a padding for an image.
def expand2square(pil_img, background_color): width, height = pil_img.size if width == height: return pil_img elif width > height: result = Image.new(pil_img.mode, (width, width), background_color) result.paste(pil_img, (0, (width - height) // 2)) return result else: result = Image.new(pil_img.mode, (height, height), background_color) result.paste(pil_img, ((height - width) // 2, 0)) return result
This function will return a new image.
3.Add padding for an image
im_new = expand2square(im, (0, 0, 0)) im_new.save('data/dst/astronaut_expand_square.jpg', quality=95)
Run this code, we will see this image: