Update app.py
Browse files
app.py
CHANGED
@@ -13,6 +13,47 @@ from typing import Optional, Union
|
|
13 |
import gradio as gr
|
14 |
import markdown
|
15 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
16 |
def encode_image(image):
|
17 |
"""
|
18 |
将PIL.Image对象或图像文件路径转换为base64编码字符串,并获取分辨率信息
|
|
|
13 |
import gradio as gr
|
14 |
import markdown
|
15 |
|
16 |
+
def base64_to_image(
|
17 |
+
base64_str: str,
|
18 |
+
remove_prefix: bool = True,
|
19 |
+
convert_mode: Optional[str] = "RGB"
|
20 |
+
) -> Union[Image.Image, None]:
|
21 |
+
"""
|
22 |
+
将Base64编码的图片字符串转换为PIL Image对象
|
23 |
+
|
24 |
+
Args:
|
25 |
+
base64_str: Base64编码的图片字符串(可带data:前缀)
|
26 |
+
remove_prefix: 是否自动去除"data:image/..."前缀(默认True)
|
27 |
+
convert_mode: 转换为指定模式(如"RGB"/"RGBA",None表示不转换)
|
28 |
+
|
29 |
+
Returns:
|
30 |
+
PIL.Image.Image 对象,解码失败时返回None
|
31 |
+
|
32 |
+
Examples:
|
33 |
+
>>> img = base64_to_image("data:image/png;base64,iVBORw0KGg...")
|
34 |
+
>>> img = base64_to_image("iVBORw0KGg...", remove_prefix=False)
|
35 |
+
"""
|
36 |
+
try:
|
37 |
+
# 1. 处理Base64前缀
|
38 |
+
if remove_prefix and "," in base64_str:
|
39 |
+
base64_str = base64_str.split(",")[1]
|
40 |
+
|
41 |
+
# 2. 解码Base64
|
42 |
+
image_data = base64.b64decode(base64_str)
|
43 |
+
|
44 |
+
# 3. 转换为PIL Image
|
45 |
+
image = Image.open(BytesIO(image_data))
|
46 |
+
|
47 |
+
# 4. 可选模式转换
|
48 |
+
if convert_mode:
|
49 |
+
image = image.convert(convert_mode)
|
50 |
+
|
51 |
+
return image
|
52 |
+
|
53 |
+
except (base64.binascii.Error, OSError, Exception) as e:
|
54 |
+
print(f"Base64解码失败: {str(e)}")
|
55 |
+
return None
|
56 |
+
|
57 |
def encode_image(image):
|
58 |
"""
|
59 |
将PIL.Image对象或图像文件路径转换为base64编码字符串,并获取分辨率信息
|