pic_base64_util.py 710 B

12345678910111213141516171819
  1. import base64
  2. import os
  3. # 图片转换为base64
  4. def pic_to_base64(path):
  5. with open(path, "rb") as image_file:
  6. try:
  7. file_name = os.path.basename(path).split(".")
  8. txt_path = os.path.join(os.path.dirname(path), file_name[0] + ".txt")
  9. with open(path, 'rb') as f, open(txt_path, mode="wb") as w_f:
  10. img_data = f.read()
  11. uri = base64.b64encode(img_data)
  12. base64_image = "data:image/png;base64," + uri.decode('utf-8')
  13. # 如果需要在浏览器展示,需要在uri前面添加:data:image/jpeg;base64,
  14. except Exception as e:
  15. print(f"img_to_base64 error:{e}")
  16. return base64_image