Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Binary Image Data From a MatPlotLib Canvas?

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

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

like image 276
Subbarker Avatar asked Aug 27 '12 15:08

Subbarker


Video Answer


1 Answers

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)

like image 200
Lior Avatar answered Sep 28 '22 04:09

Lior