create an image with border of certain width in python

I would recommend using PIL's built-in expand() function, which allows you to add a border of any colour and width to an image.

So, starting with this:

enter image description here

#!/usr/bin/env python3

from PIL import Image, ImageOps

# Open image
im = Image.open('start.png')

# Add border and save
bordered = ImageOps.expand(im, border=10, fill=(0,0,0))

bordered.save('result.png')

enter image description here


If you want different sized borders on the top/bottom from the left-right, give two widths:

bordered = ImageOps.expand(im, border=(10,50), fill=(0,0,0)) 

enter image description here


If you want different sized borders on all sides, give 4 widths:

bordered = ImageOps.expand(im, border=(10,40,80,120), fill=(0,0,0))

enter image description here

Keywords: PIL, Pillow, ImageOps, Python, border, bordering, border outside, add border, expand, pad, extent, image, image processing.