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 に答える