create an image with border of certain width in python

I have used PIL

#back_color_width 

for x in range(w):
    for y in range(h):
        if x==0 or y==0 or x==w-1 or y==h-1 :
            pixels[x,y] = back_color

I need to add a border to the image with a width on all 4 sides of image


Solution 1:

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.

Solution 2:

This is what you need to change to make the border any number of px wide:

for x in range(w):
    for y in range(h):
        if (x<border_width
            or y<border_width 
            or x>w-border_width-1 
            or y>h-border_width-1):
            pixels[x,y] = (0,0,0)

#other 3 boxes and #primary box Doesn't make boxes but instead 3 points and 1 point respectively.

Solution 3:

You are really close! You just need to change the first if statement. Right now you do have a border, but the border is 1 pixel wide on all sides. Maybe change to

if x<back_color_width or y<back_color_width or x > w+ back_color_width or y > w+back_color_width:
    pixel[x,y]=back_color