如何将pylab图形保存到可以读入PIL图像的内存文件中? [英] how to save a pylab figure into in-memory file which can be read into PIL image?

查看:31
本文介绍了如何将pylab图形保存到可以读入PIL图像的内存文件中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我的第一张照片,但从未奏效:

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.

推荐答案

记得调用 buf.seek(0) 所以 Image.open(buf) 开始读取这buf 的开头:

Remember to call buf.seek(0) so Image.open(buf) starts reading from the beginning 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图像的内存文件中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆