# 一字圖示產生
## 說明
* 設計是用來快速產生一個 64x64 的 icon,可以用作網頁的 favicon
## 第三方資料庫
* `pip install pillow`
## 程式碼
```python=
import os
from PIL import Image, ImageDraw, ImageFont
import time
# 顏色選項字典,顏色名稱對應顏色值
color_options = {
"蜜蜂紅": "#e2808a",
"玫瑰粉": "#f1ccd7",
"薄荷綠 1": "#2e765e",
"薄荷綠 2": "#638c80"
}
def create_icon(input_char, background_color, output_file):
# 設定圖像大小
size = (64, 64)
# 創建透明底圖像
image = Image.new("RGBA", size, (0, 0, 0, 0))
draw = ImageDraw.Draw(image)
# 使用選擇的背景顏色
background_rgb = tuple(int(background_color[i:i+2], 16) for i in (1, 3, 5))
# 畫圓角矩形背景
corner_radius = 12 # 圓角半徑
draw.rounded_rectangle([0, 0, size[0], size[1]], radius=corner_radius, fill=background_rgb)
# 嘗試加載指定的字體
try:
font_path = r"C:\Windows\Fonts\msjhbd.ttc" # 更換為您的字體路徑
font = ImageFont.truetype(font_path, 48) # 字體大小設定為 48
except IOError:
print("錯誤:無法找到指定字體。")
return
# 計算文字的邊界框(bounding box)大小並調整位置
bbox = draw.textbbox((0, 0), input_char, font=font) # 使用 textbbox() 獲取邊界框
text_width = bbox[2] - bbox[0] # 邊界框的寬度
text_height = bbox[3] - bbox[1] # 邊界框的高度
# 計算文字位置,將文字置中
position = ((size[0] - text_width) / 2, (size[1] - text_height) / 2)
# 畫文字的黑色描邊
outline_color = (20, 20, 20) # 黑色描邊
outline_width = 1 # 描邊寬度
# 描邊處理:繪製文字多次,稍微偏移位置來達到描邊效果
for dx in range(-outline_width, outline_width + 1):
for dy in range(-outline_width, outline_width + 1):
if dx != 0 or dy != 0:
draw.text((position[0] + dx, position[1] + dy), input_char, outline_color, font=font)
# 寫入白色文字
draw.text(position, input_char, (255, 255, 255, 255), font=font)
# 獲取桌面路徑
desktop_path = os.path.join(os.path.expanduser("~"), "Desktop")
# 設定檔案儲存位置(使用當前時間戳作為檔名)
timestamp = int(time.time()) # 使用時間戳作為檔名
output_file_path = os.path.join(desktop_path, f"{timestamp}.png")
# 保存為 PNG
image.save(output_file_path, "PNG")
print(f"已生成 {output_file_path} 圖像檔案。")
# 顯示顏色選項
print("請選擇背景顏色:")
for index, color in enumerate(color_options.keys(), 1):
print(f"{index}. {color}")
# 用戶選擇背景顏色
try:
color_choice = int(input("輸入顏色選項(1-4):"))
if 1 <= color_choice <= 4:
selected_color = list(color_options.values())[color_choice - 1]
else:
print("無效的選項。")
exit()
except ValueError:
print("請輸入有效的數字選項。")
exit()
# 輸入單一字元
input_char = input("請輸入一個字元:")
if len(input_char) == 1:
create_icon(input_char, selected_color, None)
else:
print("請只輸入一個字元。")
```