File size: 2,113 Bytes
0ab5288 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
"""
图片处理工具函数
"""
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:
# 将图片转换为base64编码
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
|