| """ |
| 图片处理工具函数 |
| """ |
|
|
| import base64 |
| from typing import List |
| from PIL import Image |
|
|
|
|
| def get_image_list(file_paths: List[str]) -> List[Image.Image]: |
| """从文件路径列表获取PIL图片列表用于展示""" |
| if not file_paths: |
| return [] |
|
|
| images = [] |
| for path in file_paths: |
| try: |
| img = Image.open(path) |
| images.append(img) |
| except Exception: |
| continue |
| return images |
|
|
|
|
| def create_image_html(file_paths: List[str]) -> str: |
| """创建图片展示的HTML代码""" |
| if not file_paths: |
| return "<div id='image-display-area'><div class='no-images'>No image uploaded - will generate from text only</div></div>" |
|
|
| html_items = [] |
| for i, path in enumerate(file_paths): |
| try: |
| |
| with open(path, "rb") as img_file: |
| img_data = base64.b64encode(img_file.read()).decode() |
| img_ext = path.split('.')[-1].lower() |
| if img_ext in ['jpg', 'jpeg']: |
| mime_type = 'image/jpeg' |
| elif img_ext == 'png': |
| mime_type = 'image/png' |
| elif img_ext == 'gif': |
| mime_type = 'image/gif' |
| elif img_ext == 'webp': |
| mime_type = 'image/webp' |
| else: |
| mime_type = 'image/jpeg' |
|
|
| img_src = f"data:{mime_type};base64,{img_data}" |
|
|
| html_items.append(f""" |
| <div class="image-item" data-index="{i}"> |
| <img src="{img_src}" alt="Uploaded image {i + 1}"> |
| <div class="delete-btn" onclick="deleteImageByIndex({i})" data-index="{i}">×</div> |
| </div> |
| """) |
| except: |
| continue |
|
|
| if not html_items: |
| return "<div id='image-display-area'><div class='no-images'>No image uploaded - will generate from text only</div></div>" |
|
|
| html_content = f""" |
| <div id='image-display-area'> |
| {''.join(html_items)} |
| </div> |
| """ |
|
|
| return html_content |
|
|