安裝依賴
# 系統級安裝 ImageMagick
# Ubuntu/Debian: sudo apt-get install libmagickwand-dev
# CentOS: sudo yum install ImageMagick-devel
# macOS: brew install imagemagick
# Python 綁定
pip install PythonMagick # 或 pip install Wand (更現代、Pythonic)
基礎轉換代碼
from PythonMagick import Image
img = Image("input.jpg")
img.sample("128x128") # 縮放至 128x128(ICO 常用尺寸)
img.write("output.ico") # 自動識別 ICO 格式
多尺寸 ICO(單文件包含多種分辨率)
from PythonMagick import Image, ImageList
sizes = [(16,16), (32,32), (48,48), (64,64), (128,128), (256,256)]
il = ImageList()
for w, h in sizes:
img = Image("input.jpg")
img.sample(f"{w}x{h}")
il.append(img)
il.write("favicon.ico")
現代替代:Wand (ctypes 綁定,更穩定)
from wand.image import Image as WImage
with WImage(filename="input.jpg") as img:
# 單尺寸
img.resize(128, 128)
img.save(filename="out.ico")
# 多尺寸
with WImage() as ico:
for w, h in sizes:
with img.clone() as frame:
frame.resize(w, h)
ico.sequence.append(frame)
ico.save(filename="favicon.ico")
常見問題
ImportError: libMagickWand.so → 系統未裝 ImageMagick 或版本不匹配
- ICO 透明背景:源圖需為 PNG 透明,JPG 無 Alpha 通道
- 大尺寸 (256px) ICO 實為 PNG 壓縮,需 ImageMagick 7+ 支持