Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
981 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...