Pillow (PIL 友善分支) 是 Python 影像處理標準庫,支援格式轉換、幾何變換、像素操作、濾鏡、繪圖與色彩增強。本文透過完整類別封裝示範核心功能與實戰技巧。
pip install Pillow
from PIL import Image, ImageDraw, ImageEnhance, ImageFilter, ImageFont
class ImageProcessor:
def __init__(self, input_path: str, output_path: str):
self.img = Image.open(input_path)
self.output_path = output_path
def resize(self, percent: float = 100, width: int = None, height: int = None):
"""縮放:百分比或指定寬高"""
w, h = self.img.size
if width and height:
new_size = (width, height)
else:
new_size = (int(w * percent / 100), int(h * percent / 100))
resized = self.img.resize(new_size, Image.Resampling.LANCZOS) # 高品質重採樣
resized.save(self.output_path)
self.img = resized # 更新內部狀態
return self
def rotate(self, angle: float, expand: bool = True):
"""旋轉:expand=True 避免裁切"""
rotated = self.img.rotate(angle, expand=expand, resample=Image.Resampling.BICUBIC)
rotated.save(self.output_path)
self.img = rotated
return self
def save_as(self, format_path: str):
"""轉換格式 (由副檔名決定)"""
self.img.save(format_path)
return self
def draw_shapes(self):
"""繪製幾何圖形"""
draw = ImageDraw.Draw(self.img)
w, h = self.img.size
# 對角線
draw.line([(0, 0), (w-1, h-1)], fill='white', width=2)
draw.line([(0, h-1), (w-1, 0)], fill='white', width=2)
# 橢圓 (外接矩形)
draw.ellipse([0, 0, w-1, h-1], outline='white', width=2)
# 矩形
draw.rectangle([10, 10, w-10, h-10], outline='red', width=3)
# 文字 (需字型檔)
try:
font = ImageFont.truetype("arial.ttf", 24)
draw.text((20, 20), "Pillow Demo", fill='yellow', font=font)
except OSError:
draw.text((20, 20), "Pillow Demo", fill='yellow')
self.img.save(self.output_path)
return self
def enhance(self):
"""色彩/銳度/對比度增強"""
# 亮度
enhancer = ImageEnhance.Brightness(self.img)
self.img = enhancer.enhance(1.2) # 1.0 原始,>1 變亮
# 銳度
enhancer = ImageEnhance.Sharpness(self.img)
self.img = enhancer.enhance(2.0)
# 對比度
enhancer = ImageEnhance.Contrast(self.img)
self.img = enhancer.enhance(1.3)
# 色彩飽和度
enhancer = ImageEnhance.Color(self.img)
self.img = enhancer.enhance(1.2)
self.img.save(self.output_path)
return self
def apply_filters(self):
"""內建濾鏡"""
self.img = self.img.filter(ImageFilter.SHARPEN) # 銳化
self.img = self.img.filter(ImageFilter.EDGE_ENHANCE) # 邊緣增強
self.img = self.img.filter(ImageFilter.BLUR) # 模糊
self.img = self.img.filter(ImageFilter.GaussianBlur(radius=2)) # 高斯模糊
self.img = self.img.filter(ImageFilter.EMBOSS) # 浮雕
self.img.save(self.output_path)
return self
def crop(self, box: tuple):
"""裁切: (left, upper, right, lower)"""
self.img = self.img.crop(box)
self.img.save(self.output_path)
return self
def convert_mode(self, mode: str = 'RGB'):
"""模式轉換: RGB, RGBA, L (灰階), CMYK, 1 (二值)"""
self.img = self.img.convert(mode)
self.img.save(self.output_path)
return self
def get_info(self):
print(f"Size: {self.img.size}, Mode: {self.img.mode}, Format: {self.img.format}")
return self
# 使用範例
if __name__ == '__main__':
processor = ImageProcessor('input.jpg', 'output.jpg')
(processor
.get_info()
.resize(percent=50)
.rotate(45)
.draw_shapes()
.enhance()
.apply_filters()
.save_as('output.png'))
| 濾波器 | 品質 | 速度 | 適用場景 |
|---|---|---|---|
NEAREST | 低 | 最快 | 像素藝術、索引色 |
BOX | 中 | 快 | 縮小 |
BILINEAR | 中 | 中 | 一般用途 |
HAMMING | 中高 | 中 | 縮小 |
BICUBIC | 高 | 較慢 | 放大、高品質 |
LANCZOS | 最高 | 最慢 | 專業級縮放 (推薦) |
# 像素存取物件 (C 級速度)
px = img.load()
px[10, 20] = (255, 0, 0) # 設定單點
# 批量像素操作 (NumPy 互操作)
import numpy as np
arr = np.array(img) # Image -> ndarray (H, W, C)
arr[:, :, 0] = 255 - arr[:, :, 0] # 反轉紅通道
img = Image.fromarray(arr) # ndarray -> Image
from pathlib import Path
input_dir = Path('photos')
output_dir = Path('thumbnails')
output_dir.mkdir(exist_ok=True)
for img_path in input_dir.glob('*.jpg'):
with Image.open(img_path) as img:
img.thumbnail((300, 300), Image.Resampling.LANCZOS)
img.save(output_dir / f'{img_path.stem}_thumb.jpg', quality=85, optimize=True)
def grid_montage(images: list, cols: int, gap: int = 5):
rows = (len(images) + cols - 1) // cols
max_w = max(img.width for img in images)
max_h = max(img.height for img in images)
canvas_w = cols * max_w + (cols - 1) * gap
canvas_h = rows * max_h + (rows - 1) * gap
canvas = Image.new('RGB', (canvas_w, canvas_h), 'white')
for idx, img in enumerate(images):
r, c = divmod(idx, cols)
x = c * (max_w + gap)
y = r * (max_h + gap)
canvas.paste(img, (x, y))
return canvas
def add_watermark(base_img: Image.Image, watermark: Image.Image,
position: str = 'bottom-right', opacity: float = 0.5):
# 調整水印透明度
if watermark.mode != 'RGBA':
watermark = watermark.convert('RGBA')
alpha = watermark.split()[3]
alpha = alpha.point(lambda x: int(x * opacity))
watermark.putalpha(alpha)
# 計算位置
bw, bh = base_img.size
ww, wh = watermark.size
positions = {
'top-left': (0, 0),
'top-right': (bw - ww, 0),
'bottom-left': (0, bh - wh),
'bottom-right': (bw - ww, bh - wh),
'center': ((bw - ww)//2, (bh - wh)//2),
}
base_img.paste(watermark, positions[position], watermark)
return base_img