How to pad an image using the pillow module in Python
The pillow module is built on top of the
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 Imageimport urllib.request#download imageurllib.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 instanceimg = Image.open("test_image.png")#get current image width and heightimg_width, img_height = img.size#create new imagenew_img = Image.new(img.mode, (img_width+1000, img_height+1000), (255, 0, 255))#place old image on new imagenew_img.paste(img, (100, 100))#save new imagenew_img.save('output/new_image.png')
Explanation
Line 5: We download the image using the
urlretrieve()method with the image name astest_image.png.Line 8: We open the image using the
Imageclass and assign the instance to a variableimg.Line 11: We get the
test_image.pngheight and width using thesizeproperty onimginstance, whereimg.sizeif of type tuple.Line 14: We create a new image
new_imgwith a height of1000more than the current image height, and with a width of1000more than the current image width. We also provide a background color usingRGBvalues.Line 17: We place the old image
test_image.pngon top of the new imagenew_imgusing thepaste()method with a left position as100and the top position as100.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