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
|
import base64
import requests
from PIL import Image
from io import BytesIO
def image_to_base64(image_path_or_url, max_dim=1024):
# 读取图片
if image_path_or_url.startswith(('http://', 'https://')):
response = requests.get(image_path_or_url)
response.raise_for_status()
img = Image.open(BytesIO(response.content))
else:
img = Image.open(image_path_or_url)
# 检查并调整尺寸
if max(img.size) > max_dim:
ratio = max_dim / max(img.size)
new_size = (int(img.width * ratio), int(img.height * ratio))
img = img.resize(new_size, Image.LANCZOS)
# 转换格式并编码
buffered = BytesIO()
img_format = img.format if img.format else 'PNG'
img.save(buffered, format=img_format)
img_bytes = buffered.getvalue()
return f"data:image/{img_format.lower()};base64," + base64.b64encode(img_bytes).decode('utf-8')
|