Pillow (PIL) 簡介
Pillow 是 PIL(Python Imaging Library) 的改進版本,提供簡單易用的影像處理功能,如 讀取圖片、縮放、旋轉、調整顏色、存儲圖片。
✅ 1. 安裝 Pillow
Pillow 不是 Python 內建套件,需要先安裝:
✅ 2. 讀取與顯示圖片
Pillow 使用 Image.open() 來讀取圖片:
✅ 3. 取得圖片資訊
print(img.format) # 取得圖片格式 (JPEG, PNG, GIF)
print(img.size) # 取得圖片大小 (寬, 高)
print(img.mode) # 取得圖片模式 (RGB, RGBA, L, CMYK)
✅ 4. 轉換圖片格式
✅ 模式 "L" 表示灰階,"RGB" 表示彩色,"RGBA" 包含透明度
✅ 5. 調整圖片大小
✅ 適用於產生縮圖(Thumbnails)
✅ 6. 旋轉與翻轉
rotated_img = img.rotate(45) # 旋轉 45 度
flipped_img = img.transpose(Image.FLIP_LEFT_RIGHT) # 左右翻轉
rotated_img.show()
flipped_img.show()
✅ 可用於圖像校正
✅ 7. 裁剪圖片
✅ 適用於提取圖片中特定區域
✅ 8. 繪製文字(需要 ImageDraw)
from PIL import ImageDraw, ImageFont
img = Image.open("example.jpg")
draw = ImageDraw.Draw(img)
draw.text((50, 50), "Hello, Pillow!", fill="white") # 在圖片上添加文字
img.show()
✅ 適用於生成海報、浮水印
✅ 9. 儲存圖片
✅ 可指定品質 (quality=0~100),數值越高品質越好
📝 總結
| 功能 | 函數 |
|---|---|
| 讀取圖片 | Image.open("image.jpg") |
| 顯示圖片 | img.show() |
| 獲取資訊 | img.size, img.mode, img.format |
| 轉灰階 | img.convert("L") |
| 調整大小 | img.resize((width, height)) |
| 旋轉圖片 | img.rotate(角度) |
| 翻轉圖片 | img.transpose(Image.FLIP_LEFT_RIGHT) |
| 裁剪圖片 | img.crop((左, 上, 右, 下)) |
| 繪製文字 | ImageDraw.Draw(img).text((x, y), "文字", fill="color") |
| 儲存圖片 | img.save("new_image.jpg") |
🚀 Pillow 適用於基礎影像處理,如格式轉換、縮放、裁剪、文字標註等! 😊