下載網路圖片、等比例縮放至指定顯示區域 (如 400x350)、保存或顯示。關鍵在於計算縮放比例,保持長寬比不變形。
def resize_image(pil_image, max_width, max_height):
"""等比例縮放 PIL Image 使其適應 max_width x max_height 區域"""
orig_w, orig_h = pil_image.size
# 計算縮放比例:取寬高比例較小者
ratio = min(max_width / orig_w, max_height / orig_h)
new_w = int(orig_w * ratio)
new_h = int(orig_h * ratio)
# 使用高品質濾鏡
return pil_image.resize((new_w, new_h), Image.LANCZOS) # Pillow 9.1+ 建議 LANCZOS
import io
import sys
from PIL import Image, ImageTk
if sys.version_info[0] == 2:
import Tkinter as tk
from urllib2 import urlopen
else:
import tkinter as tk
from urllib.request import urlopen
def download_and_resize(url, box_width, box_height, save_path=None):
# 下載
with urlopen(url) as resp:
img_data = resp.read()
# 解碼
pil_image = Image.open(io.BytesIO(img_data))
orig_w, orig_h = pil_image.size
# 縮放
resized = resize_image(pil_image, box_width, box_height)
new_w, new_h = resized.size
# 保存
if save_path:
resized.save(save_path)
print(f"已保存: {save_path} ({new_w}x{new_h})")
return resized, (orig_w, orig_h), (new_w, new_h)
def resize_image(pil_image, max_width, max_height):
orig_w, orig_h = pil_image.size
ratio = min(max_width / orig_w, max_height / orig_h)
new_w = int(orig_w * ratio)
new_h = int(orig_h * ratio)
return pil_image.resize((new_w, new_h), Image.LANCZOS)
# Tkinter 顯示範例
def show_resized_image(url, box_w=400, box_h=350):
root = tk.Tk()
resized, orig_size, new_size = download_and_resize(url, box_w, box_h)
tk_img = ImageTk.PhotoImage(resized)
label = tk.Label(root, image=tk_img, width=box_w, height=box_h, bg='white')
label.image = tk_img
label.pack(padx=10, pady=10)
fname = url.split('/')[-1]
root.title(f"{fname} 原始:{orig_size[0]}x{orig_size[1]} 縮放:{new_size[0]}x{new_size[1]}")
root.mainloop()
if __name__ == '__main__':
# 測試圖片 (1600x1200)
url = "https://freeflowerpictures.net/image/flowers/petunia/petunia-flower.jpg"
show_resized_image(url)
import os
from concurrent.futures import ThreadPoolExecutor
def batch_resize(urls, output_dir, max_w=800, max_h=600, workers=4):
os.makedirs(output_dir, exist_ok=True)
def process(url):
try:
fname = os.path.basename(url).split('?')[0]
out_path = os.path.join(output_dir, fname)
download_and_resize(url, max_w, max_h, out_path)
return f"✓ {fname}"
except Exception as e:
return f"✗ {url}: {e}"
with ThreadPoolExecutor(max_workers=workers) as executor:
results = list(executor.map(process, urls))
for r in results:
print(r)
# 使用
urls = [
"https://example.com/img1.jpg",
"https://example.com/img2.png",
]
batch_resize(urls, "resized_images")
| 格式 | 儲存參數 | 適用場景 |
|---|---|---|
| JPEG | quality=85, optimize=True | 照片、網頁圖片 |
| PNG | optimize=True | 截圖、透明背景、無損 |
| WebP | quality=80, method=6 | 現代網頁、體積更小 |
| GIF | save_all=True (動畫) | 簡單動畫 |