读图片,方法一:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
import base64
import requests
from PIL import Image
from io import BytesIO

def image_to_base64(image_path_or_url):
    if image_path_or_url.startswith('http://') or image_path_or_url.startswith('https://'):
        response = requests.get(image_path_or_url)
        response.raise_for_status()
        image_data = BytesIO(response.content)
    else:
        with open(image_path_or_url, 'rb') as image_file:
            image_data = BytesIO(image_file.read())
    
    img = Image.open(image_data)
    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')

读图片,方法二(带压缩):

 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')