Matplotlib图形图像到base64

2024-09-28 18:52:38 发布

您现在位置:Python中文网/ 问答频道 /正文

问题:需要将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

Tags: 方法图像文件夹cacheimgreaddatapng
2条回答

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

原因是cStringIO和{}都不推荐使用

import cStringIO
my_stringIObytes = cStringIO.StringIO()
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

相关问题 更多 >