将Matplotlib图像转换为base64编码。

15 浏览
0 Comments

将Matplotlib图像转换为base64编码。

问题 : 需要将matplotlib的图形图像转换为base64图像

当前解决方案 : 将matplot图像保存在缓存文件夹中,并使用read()方法读取,然后转换为base64

新问题 : 烦恼 : 需要一个解决方法,以便我不需要将图形作为图像保存在任何文件夹中。我想只使用存储在内存中的图像。无谓的I/O操作是一种不良实践。

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

admin 更改状态以发布 2023年5月22日
0
0 Comments

针对Python 3

import base64
import io 
pic_IObytes = io.BytesIO()
plt.savefig(pic_IObytes,  format='png')
pic_IObytes.seek(0)
pic_hash = base64.b64encode(pic_IObytes.read())

原因在于cStringIOcStringIO.StringIO()都已经弃用了。

0
0 Comments

import cStringIO
my_stringIObytes = cStringIO.StringIO()
plt.savefig(my_stringIObytes, format='jpg')
my_stringIObytes.seek(0)
my_base64_jpgData = base64.b64encode(my_stringIObytes.read())

[编辑] 在Python3中应该是这样的

import io
my_stringIObytes = io.BytesIO()
plt.savefig(my_stringIObytes, format='jpg')
my_stringIObytes.seek(0)
my_base64_jpgData = base64.b64encode(my_stringIObytes.read()).decode()

我认为至少......基于文档http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.savefig

0