7

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.

1 Answer 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)

Sign up to request clarification or add additional context in comments.

4 Comments

Glad to help :) May I ask why do you need to access the raw png data of the canvas?
It's being attached to an email, and I couldn't see the need to keep around the files afterwards.
Oh, that's interesting. I would change the original question and add this explanation, so other people can search "email matplotlib plots" and find this question/answer.
Complete example using io.BytesIO: stackoverflow.com/questions/18766060/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.