2025.4.8

以下是一个使用Python将图片转换为Base64编码并传递到前端的示例代码:

import base64
from flask import Flask, render_template

app = Flask(__name__)

def image_to_base64(image_path):
    with open(image_path, "rb") as image_file:
        encoded_string = base64.b64encode(image_file.read()).decode('utf-8')
    return encoded_string

@app.route('/')
def show_image():
    # 替换为你的图片路径
    image_path = "example.jpg"
    
    # 获取Base64编码
    image_base64 = image_to_base64(image_path)
    
    # 确定图片类型(这里以jpg为例,如果是png请改为image/png)
    mime_type = "image/jpeg"
    
    # 构建Data URL
    image_data_url = f"data:{mime_type};base64,{image_base64}"
    
    # 传递给前端HTML模板
    return render_template('show_image.html', image_data_url=image_data_url)

if __name__ == '__main__':
    app.run(debug=True)

对应的HTML模板文件(templates/show_image.html)内容如下:

<!DOCTYPE html>
<html>
<head>
    <title>显示Base64图片</title>
</head>
<body>
    <h1>Base64编码图片示例</h1>
    <img src="{{ image_data_url }}" alt="Base64编码图片">
</body>
</html>

说明:

  1. image_to_base64函数读取图片文件并将其转换为Base64编码字符串
  2. 我们使用Flask作为Web框架来演示如何将编码传递给前端
  3. 在前端,Base64编码的图片可以通过Data URL方式直接在<img>标签的src属性中使用
  4. Data URL的格式为:data:[MIME类型];base64,[Base64编码数据]

注意事项:

  • 确保图片文件存在且路径正确
  • 根据实际图片类型设置正确的MIME类型(如PNG用image/png
  • 对于大图片,Base64编码会增加约33%的数据量,可能影响性能

如果你不需要Web框架,只需要转换代码,核心部分是这样的:

import base64

def image_to_base64(image_path):
    with open(image_path, "rb") as image_file:
        return base64.b64encode(image_file.read()).decode('utf-8')

# 使用示例
base64_string = image_to_base64("example.jpg")
print(base64_string)  # 这会打印出Base64编码字符串
posted @ 2025-04-08 23:01  258333  阅读(35)  评论(0)    收藏  举报