从MatPlotLib画布中获取二进制图像数据?

问题描述:

我正在尝试从matplotlib画布中获取二进制数据,因此我可以将其附加到电子邮件中,但我发现这样做的唯一方法是:

I'm trying to get the binary data from a matplotlib canvas so I can attach it to an email, but the only way I've found to do so is by saying:

filename = 'image.png'
canvas.print_figure(filename)
with open(filename, 'rb') as image:
    return image.read()

我真的希望避免使用磁盘IO,因为我不

I'd really like to avoid the Disk IO since I don't need to hold onto the file afterwards.

使用 StringIO 对象作为文件对象,可以被赋予 print_png canvas功能。

Use a StringIO object as a file object, which can be given to the print_png canvas function.

from cStringIO import StringIO
sio = StringIO()
canvas.print_png(sio)
return sio.getvalue()

(如果您使用的是Python 3,请使用 io.BytesIO 而不是 cStringIO

(if you're using Python 3, use io.BytesIO instead of cStringIO)