準備兩張圖:
將源圖貼到白底畫布,再用圓角圖作為 mask 疊合,透明區變透明,實現圓角。
from PIL import Image
source = Image.open('flower.png').convert('RGBA')
mask = Image.open('rounded_mask.png').convert('L') # 灰度圖作為 Alpha
# 創建白底畫布
canvas = Image.new('RGBA', source.size, (255,255,255,255))
# 貼源圖
canvas.paste(source, (0,0), source) # source 自帶 alpha 作為 mask
# 應用圓角 mask
canvas.putalpha(mask)
canvas.save('rounded_icon.png')
def make_rounded(image_path, radius, output_path, bg_color=(255,255,255,255)):
img = Image.open(image_path).convert('RGBA')
w, h = img.size
# 生成圓角矩形蒙版
mask = Image.new('L', (w, h), 0)
from PIL import ImageDraw
draw = ImageDraw.Draw(mask)
draw.rounded_rectangle([0, 0, w, h], radius=radius, fill=255)
# 合成
canvas = Image.new('RGBA', (w, h), bg_color)
canvas.paste(img, (0,0), img)
canvas.putalpha(mask)
canvas.save(output_path)
make_rounded('avatar.jpg', 30, 'avatar_rounded.png')
canvas.save('rounded.webp', 'WEBP', quality=80, method=6, lossless=False)