萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> HTML 腳本教學

Python PIL 實現圓角圖標生成:蒙版疊合技術

原理:Alpha 蒙版合成

準備兩張圖:

  • 源圖:任意內容
  • 圓角蒙版:白色圓角矩形(不透明區)+ 透明背景

將源圖貼到白底畫布,再用圓角圖作為 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')

WebP 輸出(更小體積)

canvas.save('rounded.webp', 'WEBP', quality=80, method=6, lossless=False)
copyright © 萬盛學電腦網 all rights reserved