本文介绍了如何将pylab图形保存到可读取到PIL映像的内存文件中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
PIL的新手,但想从中快速获得解决方案.以下是我的第一个失败的镜头:
new to PIL, but want to get a quick solution out of it. The following is my first shot which never works:
import cStringIO
import pylab
from PIL import Image
pylab.figure()
pylab.plot([1,2])
pylab.title("test")
buffer = cStringIO.StringIO()
pylab.savefig(buffer, format='png')
im = Image.open(buffer.read())
buffer.close()
错误提示
Traceback (most recent call last):
File "try.py", line 10, in <module>
im = Image.open(buffer.read())
File "/awesomepath/python2.7/site-packages/PIL/Image.py", line 1952, in open
fp = __builtin__.open(fp, "rb")
有什么想法吗?我不希望该解决方案包含额外的程序包,谢谢.
any ideas? I don't want the solution to involve extra packages, thanks.
推荐答案
请记住要调用buf.seek(0)
,以便Image.open(buf)
开始从buf
的开头:
Remember to call buf.seek(0)
so Image.open(buf)
starts reading from thebeginning of the buf
:
import io
from PIL import Image
import matplotlib.pyplot as plt
plt.figure()
plt.plot([1, 2])
plt.title("test")
buf = io.BytesIO()
plt.savefig(buf, format='png')
buf.seek(0)
im = Image.open(buf)
im.show()
buf.close()
这篇关于如何将pylab图形保存到可读取到PIL映像的内存文件中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!