Matplotlib 图形图像转 base64 [英] Matplotlib graphic image to base64
问题描述
问题:需要将matplotlib的图形图像转换为base64图像
Problem : Need to transform a graphic image of matplotlib to a base64 image
当前解决方案:将matplot图像保存在缓存文件夹中,使用read()方法读取,然后转换为base64
Current Solution : Save the matplot image in a cache folder and read it with read() method and then convert to base64
新问题:烦恼:需要一个解决方法,所以我不需要将图形另存为任何文件夹中的图像.我只想使用内存中的图像.进行不必要的 I/O 是一种不好的做法.
New Problem : Annoyance : Need a workaround so I dont need to save the graphic as image in any folder. I want to just use the image in the memory. Doing unnecessary I/O is a bad practice.
def save_single_graphic_data(data, y_label="Loss", x_label="Epochs", save_as="data.png"):
total_epochs = len(data)
plt.figure()
plt.clf()
plt.plot(total_epochs, data)
ax = plt.gca()
ax.ticklabel_format(useOffset=False)
plt.ylabel(y_label)
plt.xlabel(x_label)
if save_as is not None:
plt.savefig(save_as)
plt.savefig("cache/cached1.png")
cached_img = open("cache/cached1.png")
cached_img_b64 = base64.b64encode(cached_img.read())
os.remove("cache/cached1.png")
return cached_img_b64
推荐答案
import cStringIO
my_stringIObytes = cStringIO.StringIO()
plt.savefig(my_stringIObytes, format='jpg')
my_stringIObytes.seek(0)
my_base64_jpgData = base64.b64encode(my_stringIObytes.read())
[edit]在python3中应该是
[edit] in python3 it should be
import io
my_stringIObytes = io.BytesIO()
plt.savefig(my_stringIObytes, format='jpg')
my_stringIObytes.seek(0)
my_base64_jpgData = base64.b64encode(my_stringIObytes.read())
我认为至少......基于文档http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.savefig
I think at least ... based on the documentation http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.savefig
这篇关于Matplotlib 图形图像转 base64的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!