Get binary image data from MatPlotLib canvas?

I am trying to get binary data from matplotlib canvas, so I can attach it to an email, but the only way I found is to say:

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

I would really like to avoid Disk IO, since after that I do not need to hold the file.

+6
source share
1 answer

Use the StringIO object as a file object that can be specified for the canvas print_png function.

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

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

+5
source

Source: https://habr.com/ru/post/923882/


All Articles