Python PIL – Add a border to image

In this post we will be creating a Python script that will add a border to an existing image, to do this we will be using the Python Imaging Library also known as PIL enabling us to image processing capabilities.

See the sample of Python code where we utilise the PIL library to add a border to an image and save it as a new file. To help us achieve this we utilize the ‘ImageOps.expand()’ method which adds a border to the image given the border width in pixels and pixel fill colour.

Below our border is 10 pixels wide and coloured black.

from PIL import Image, ImageOps

img = Image.open('image.png')

img = ImageOps.expand(img, border=10, fill='black')

img.save('border_image.png')

See below our image before the adding of the border.

Image before border

See below our image with a border.

image with border

Take a look at some of our other content around the Python programming language by clicking here.

Leave a Reply