繁体   English   中英

如何在 Python 中将内存中保存的图像编码为 Base64?

[英]How to encode a image saved in memory to Base64 in Python?

我已经将图像保存在内存中,但我需要在 base64 中对图像进行编码。 目的是将编码存储在 Pandas DataFrame 中,因为此代码位于将在 SQL Server 中运行的 python 脚本中。 我只需要编码步骤。 其他一切都运行良好。

buf = io.BytesIO()
plt.savefig(buf, format='png')
buf.seek(0)
im = Image.open(buf)

with open(im, "rb") as image_file:
    encoded_string = base64.b64encode(image_file.read())

total_description['cartaX'] = 'data:image/png;base64,' + str(encoded_string) 

buf.close()

这只是将绘图以图像格式保存在内存中并尝试对图像进行编码的代码。

当我保存图像时,我可以编码,但是当我存储在内存中时,我得到一个错误。 我该怎么做? 保存图像它不是一个选项,因为它正在数据库中运行

实际情况我已经可以将de图像保存在内存中并在VS代码中以base64编码de图像。 但在SQL server 中不运行。 这是我在 VS 代码上使用和工作的代码

my_stringIObytes = io.BytesIO()                 # create file in memory
plt.savefig(my_stringIObytes, format='png')     # save file in memory 
my_stringIObytes.seek(0)                        # move to the beginning of file
my_base64_jpgData = base64.b64encode(my_stringIObytes.read())
total_description['cartaX'] = 'data:image/png;base64,' + str(my_base64_jpgData) 

你会建议我为 SQL Server 中的这项工作进行哪些更改?


我在互联网上找到了这个代码片段:
 import base64 def get_base64_encoded_image(image_path): with open(image_path, "rb") as img_file: return base64.b64encode(img_file.read()).decode('utf-8')

点击
希望这些是有帮助的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM