Skip to content
Related Articles

Related Articles

Add padding to the image with Python – Pillow
  • Last Updated : 16 Mar, 2021

Prerequisites: Pillow(python library)

Padding is the space between the contents, the container, and the border. An image can be considered content to some container and extra padding can be added to it. This article depicts how this can be done.  Padding can be added by straightaway supplying the values for the side to be padded. These values can then be passed to the function to create a new image.

Installation

This module is not preloaded with Python. So to install it execute the following command in the command-line:

pip install pillow

Approach

  • Import module
  • Open image
  • Set values for padding
  • Set different dimensions for image
  • Pass the padding values to the image
  • Save new image

Input Image:



Program :

Python3




from PIL import Image
  
image = Image.open("input.jpg")
  
right = 100
left = 100
top = 100
bottom = 100
  
width, height = image.size
  
new_width = width + right + left
new_height = height + top + bottom
  
result = Image.new(image.mode, (new_width, new_height), (0, 0, 255))
  
result.paste(image, (left, top))
  
result.save('output.jpg')

Output:

The output generated is just the input image with a padding added to it. Here it appears as a border, since the values given for each side were equal. For different values non-uniform padding can be observed.

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course

My Personal Notes arrow_drop_up
Recommended Articles
Page :