7

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

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

我真的很想避免磁盘 IO,因为之后我不需要保留文件。

4

1 回答 1

6

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

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

于 2012-08-27T15:43:52.977 回答