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.
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
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With