PIL如何向粘贴的图像添加圆角?

2024-10-04 09:18:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经在背景上粘贴了一个图像,但我目前面临一个问题,我不知道如何使粘贴图像的角变圆。我想对保存在下面脚本中的用户变量中的图像进行四舍五入

输出:Output Image。 我想要的:Expected output

import io, requests
from PIL import Image

user = Image.open(io.BytesIO(requests.get('https://cdn.discordapp.com/attachments/710929396013334608/720738818667446282/65578836_2994649093913191_1181627229703939865_n.jpg').content)).resize((40, 40))
back = Image.new('RGB', (646, 85), (54, 57, 63))
byteImg = io.BytesIO()
back.save(byteImg, format='PNG', quality=95)
back = Image.open(io.BytesIO(byteImg.getvalue()))
back.paste(user, (15, 23))

back.save('done.png') # Should save to the current directory

Tags: io图像imageimport脚本粘贴saveback
1条回答
网友
1楼 · 发布于 2024-10-04 09:18:13

我学会了如何创作图像。我们能够创建并合成一个面具图像Image.composite来自PIL库。我引用了Composite two images according to a mask image with Python, Pillow这篇文章

from PIL import Image, ImageDraw, ImageFilter
import matplotlib.pyplot as plt

ims = Image.open('./lena_square.jpg')

blur_radius = 0
offset = 4
back_color = Image.new(ims.mode, ims.size, (0,0,0))
offset = blur_radius * 2 + offset
mask = Image.new("L", ims.size, 0)
draw = ImageDraw.Draw(mask)
draw.ellipse((offset, offset, ims.size[0] - offset, ims.size[1] - offset), fill=255)
mask = mask.filter(ImageFilter.GaussianBlur(blur_radius))

ims_round = Image.composite(ims, back_color, mask)
plt.imshow(ims_round)
ims_round.save('./lena_mask.jpg', quality=95)

enter image description hereenter image description here

相关问题 更多 >