Files
FoodClassifier/data_management/utils/image_loader.py
T

79 lines
1.7 KiB
Python

"""
图片加载工具
用于从URL加载图片并转换为PIL/CTkImage格式
"""
import io
import requests
from PIL import Image
from typing import Optional
import customtkinter as ctk
def load_image_from_url(
url: str,
size: tuple = (150, 150),
timeout: int = 10
) -> Optional[ctk.CTkImage]:
"""
从URL加载图片
Args:
url: 图片URL
size: 目标尺寸 (width, height)
timeout: 超时时间(秒)
Returns:
CTkImage对象,失败返回None
"""
try:
# 下载图片
response = requests.get(url, timeout=timeout)
response.raise_for_status()
# 转换为PIL Image
image_data = io.BytesIO(response.content)
pil_image = Image.open(image_data)
# 转换为RGB(防止RGBA等格式问题)
if pil_image.mode != 'RGB':
pil_image = pil_image.convert('RGB')
# 创建CTkImage
ctk_image = ctk.CTkImage(
light_image=pil_image,
dark_image=pil_image,
size=size
)
return ctk_image
except Exception as e:
print(f"加载图片失败 {url}: {e}")
return None
def create_placeholder_image(
size: tuple = (150, 150),
text: str = "加载失败"
) -> ctk.CTkImage:
"""
创建占位图片
Args:
size: 图片尺寸
text: 显示文字
Returns:
CTkImage对象
"""
# 创建灰色背景图片
pil_image = Image.new('RGB', size, color=(200, 200, 200))
ctk_image = ctk.CTkImage(
light_image=pil_image,
dark_image=pil_image,
size=size
)
return ctk_image