file_helper.py 502 B

1234567891011121314151617
  1. import os
  2. import mimetypes
  3. import base64
  4. def encode_image(path: str):
  5. # 根据文件扩展名获取 MIME 类型
  6. mime_type, _ = mimetypes.guess_type(path)
  7. if mime_type is None:
  8. mime_type = 'image/jpeg' # 默认使用 jpeg 类型
  9. # 将图片编码为 base64 字符串
  10. with open(path, "rb") as image_file:
  11. encoded_string = base64.b64encode(image_file.read())
  12. base64Str = encoded_string.decode("utf-8")
  13. return f"data:{mime_type};base64,{base64Str}"