摘要
在網站開發或應用程序設計中,常需將高品質PNG圖像轉換為ICO格式圖標。本文提供一份基于Pillow庫實現的,能夠完美保留透明背景且支持導出圓角矩形/方形圖標的格式轉換腳本。
源碼示例
圓角方形
from PIL import Image, ImageDraw, ImageOpsdef create_rounded_png(image_path, output_path, size, corner_radius):"""將指定的圖片文件轉換為n*n的圓角PNG圖片。:param image_path: 輸入圖片文件的路徑:param output_path: 輸出PNG文件的路徑:param size: 圖標的大小,n*n:param corner_radius: 圓角的半徑"""with Image.open(image_path) as img:# 調整圖片大小到n*nresized_img = img.resize((size, size), Image.ANTIALIAS)# 創建一個與原圖大小相同的透明背景圖片用于繪制圓角蒙版mask = Image.new('L', (size, size), 0)draw = ImageDraw.Draw(mask)# 繪制圓角矩形蒙版draw.rounded_rectangle([(0, 0), (size - 1, size - 1)], corner_radius, fill=255)# 應用圓角蒙版到原圖上rounded_img = ImageOps.fit(resized_img, mask.size, centering=(0.5, 0.5))rounded_img.putalpha(mask)# 保存為PNG文件rounded_img.save(output_path)# 示例用法
create_rounded_png('path/to/your/PNG_img.png', 'path/to/your/ico_file.ico', 512, 69)
任意 寬×高 圓角矩形
from PIL import Image, ImageDraw, ImageOpsdef create_rounded_icon(image_path, output_path, size, corner_radius):"""將指定的圖片文件轉換為指定尺寸的圓角矩形ICO圖標。:param image_path: 輸入圖片文件的路徑:param output_path: 輸出ICO文件的路徑:param size: 圖標的大小,格式為(width, height):param corner_radius: 圓角的半徑"""with Image.open(image_path) as img:# 調整圖片大小到指定尺寸resized_img = img.resize(size, Image.ANTIALIAS)# 創建一個與原圖大小相同的透明背景圖片用于繪制圓角蒙版mask = Image.new('L', size, 0)draw = ImageDraw.Draw(mask)# 繪制圓角矩形蒙版draw.rounded_rectangle([(0, 0), (size[0] - 1, size[1] - 1)], corner_radius, fill=255)# 應用圓角蒙版到原圖上rounded_img = ImageOps.fit(resized_img, mask.size, centering=(0.5, 0.5))rounded_img.putalpha(mask)# 保存為ICO文件rounded_img.save(output_path, format='ICO')# 示例用法
create_rounded_icon('path/to/your/PNG_img.png', 'path/to/your/rounded_icon.ico', (512, 256), 69)
實際操作中可根據自己的需求調整
size
,corner_radius
等參數,改變圖標和蒙版的形狀和位置等。