简体   繁体   English

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

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

I already have the image saved in memory but I need to encode the image in base64.我已经将图像保存在内存中,但我需要在 base64 中对图像进行编码。 The intent is store the encode in a Pandas DataFrame because this code is inside a python script that will run inside SQL Server.目的是将编码存储在 Pandas DataFrame 中,因为此代码位于将在 SQL Server 中运行的 python 脚本中。 I only need the encoding step.我只需要编码步骤。 Everything else is working really well.其他一切都运行良好。

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()

This is only the code for saving the plot in a image format in memory and trying to encode the image.这只是将绘图以图像格式保存在内存中并尝试对图像进行编码的代码。

When I have the image saved I can encode, but when I store in memory I get an error.当我保存图像时,我可以编码,但是当我存储在内存中时,我得到一个错误。 How can I do it?我该怎么做? Save the image it's not a option because this is running in the database保存图像它不是一个选项,因为它正在数据库中运行

Actual status I already can save de image in memory and encode de image in base64 in the VS code.实际情况我已经可以将de图像保存在内存中并在VS代码中以base64编码de图像。 But in the SQL server do not run.但在SQL server 中不运行。 This is the code that I use and works on VS code这是我在 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) 

What would you suggest I change for this work in SQL Server?你会建议我为 SQL Server 中的这项工作进行哪些更改?


I found this code snippet on internet: 我在互联网上找到了这个代码片段:
 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')

click 点击
Hope these is helpful.希望这些是有帮助的。

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

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