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