如何在图像周围添加圆形边框? [英] How to add a round border around an image?
问题描述
我有一个矩形图像,我想将其圆角,然后在其上添加黑色边框(这样边框也是圆形的).
I have a rectangle image, and I would like to round its corners and then add a black border to it (so the border is also round).
有没有简单的方法来实现它?
Is there an easy way to achieve it?
那将是期望的输出:
推荐答案
我很想用SVG绘制圆角矩形以进行更改-尤其是因为有人认为我一直使用ImageMagick;-)
I fancied my hand at drawing rounded rectangles with SVG for a change - not least because somebody thinks I always use ImageMagick ;-)
#!/usr/bin/env python3
from PIL import ImageOps, Image
from cairosvg import svg2png
from io import BytesIO
def frame(im, thickness=5):
# Get input image width and height, and calculate output width and height
iw, ih = im.size
ow, oh = iw+2*thickness, ih+2*thickness
# Draw outer black rounded rect into memory as PNG
outer = f'<svg width="{ow}" height="{oh}" style="background-color:none"><rect rx="20" ry="20" width="{ow}" height="{oh}" fill="black"/></svg>'
png = svg2png(bytestring=outer)
outer = Image.open(BytesIO(png))
# Draw inner white rounded rect, offset by thickness into memory as PNG
inner = f'<svg width="{ow}" height="{oh}"><rect x="{thickness}" y="{thickness}" rx="20" ry="20" width="{iw}" height="{ih}" fill="white"/></svg>'
png = svg2png(bytestring=inner)
inner = Image.open(BytesIO(png)).convert('L')
# Expand original canvas with black to match output size
expanded = ImageOps.expand(im, border=thickness, fill=(0,0,0)).convert('RGB')
# Paste expanded image onto outer black border using inner white rectangle as mask
outer.paste(expanded, None, inner)
return outer
# Open image, frame it and save
im = Image.open('monsters.jpg')
result = frame(im, thickness=10)
result.save('result.png')
输出图像
输入图片
您可以使用rx
和ry
来更改拐角的半径.
You can play with rx
and ry
to change the radius of the corners.
这里有outer
,inner
和expanded
-如您所见,它们的大小都相同,以便于彼此组合.
Here are outer
, inner
and expanded
- as you can see they are all the same size as each other for easy composing atop each other.
其他想法:
- 您还可以通过在黑盒中绘制白色矩形并在其上运行中值滤镜或某些形态腐蚀来创建圆角.如果您对此进行过滤:
使用15x15中值滤镜,您会得到:
with a 15x15 median filter, you get this:
以防万一有人需要 ImageMagick 解决方案:
Just in case anyone wants an ImageMagick solution:
#!/bin/bash
# Get width and height of input image
read iw ih < <(identify -format "%w %h" monsters.jpg)
# Calculate size of output image, assumes thickness=10
((ow=iw+20))
((oh=ih+20))
magick -size ${ow}x${oh} xc:none -fill black -draw "roundrectangle 0,0 $ow,$oh 20,20" \
\( -size ${iw}x${ih} xc:black -fill white -draw "roundrectangle 0,0,$iw,$ih 20,20" monsters.jpg -compose darken -composite \) \
-gravity center -compose over -composite result.png
关键字:Python,图像处理,圆角,圆角,边框,SVG,cairo,cairosvg,SVG到PNG,SVG作为PNG,SVG到PIL,PIL,Pillow.
Keywords: Python, image processing, round corners, rounded corners, border, SVG, cairo, cairosvg, SVG to PNG, SVG as PNG, SVG to PIL, PIL, Pillow.
这篇关于如何在图像周围添加圆形边框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!