相关疑难解决方法(0)

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
Run Code Online (Sandbox Code Playgroud)

python matplotlib python-2.7

9
推荐指数
3
解决办法
3756
查看次数

标签 统计

matplotlib ×1

python ×1

python-2.7 ×1