How to pad an image using the pillow module in Python

The pillow module is built on top of the PILPython Image Library module for image processing. In this answer, we'll learn to pad an image using the pillow module in Python.

The idea is to create a new image with more width and height than the current image has and place the old image on top of the new image with a specified position.

Let's take a look at an example of this.

Example

from PIL import Image
import urllib.request
#download image
urllib.request.urlretrieve('https://images.unsplash.com/photo-1573776396359-5576727fa835?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=465&q=80', 'test_image.png')
#get Image instance
img = Image.open("test_image.png")
#get current image width and height
img_width, img_height = img.size
#create new image
new_img = Image.new(img.mode, (img_width+1000, img_height+1000), (255, 0, 255))
#place old image on new image
new_img.paste(img, (100, 100))
#save new image
new_img.save('output/new_image.png')

Explanation

  • Line 5: We download the image using the urlretrieve() method with the image name as test_image.png.

  • Line 8: We open the image using the Image class and assign the instance to a variable img.

  • Line 11: We get the test_image.png height and width using the size property on img instance, where img.size if of type tuple.

  • Line 14: We create a new image new_img with a height of 1000 more than the current image height, and with a width of 1000 more than the current image width. We also provide a background color using RGB values.

  • Line 17: We place the old image test_image.png on top of the new image new_img using the paste() method with a left position as 100 and the top position as 100.

  • Line 20: We save the image using the save() method.

Now the image has padding as follows:

  • Left: 100

  • Right: 900

  • Top: 100

  • Bottom: 900

The right and bottom paddings are calculated as follows:

Right = 1000 - Left => 1000 - 100 = 900

Bottom = 1000 - top => 1000 - 100 = 900

The new image is 1000px larger in width and height, so after pasting the old image on top of the new image we are only left with 1000px in height and width.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved