从MatPlotLib画布中获取二进制图像数据? [英] Get Binary Image Data From a MatPlotLib Canvas?
本文介绍了从MatPlotLib画布中获取二进制图像数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试从matplotlib画布中获取二进制数据,因此我可以将其附加到电子邮件中,但我发现这样做的唯一方法是:
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()
我真的希望避免使用磁盘IO,因为我不
I'd really like to avoid the Disk IO since I don't need to hold onto the file afterwards.
推荐答案
使用 StringIO
对象作为文件对象,可以被赋予 print_png
canvas功能。
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()
(如果您使用的是Python 3,请使用 io.BytesIO
而不是 cStringIO
)
(if you're using Python 3, use io.BytesIO
instead of cStringIO
)
这篇关于从MatPlotLib画布中获取二进制图像数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文