![](/img/trans.png)
[英]How to convert Matplotlib figure to PIL Image object (without saving image)
[英]Python save matplotlib figure on an PIL Image object
HI,我是否有可能从matplotlib创建一个图像并将其保存在我从PIL创建的图像对象上? 听起来很难? 谁能帮我?
要在Django Framework的网页中呈现Matplotlib图像:
创建matplotlib图
将其保存为png文件
将此图像存储在字符串缓冲区中(使用PIL)
将此缓冲区传递给Django的HttpResponse (设置mime类型图像/ png)
它返回一个响应对象 (在这种情况下为渲染图)。
换句话说,所有这些步骤都应放在views.py中的Django 视图函数中:
from matplotlib import pyplot as PLT
import numpy as NP
import StringIO
import PIL
from django.http import HttpResponse
def display_image(request) :
# next 5 lines just create a matplotlib plot
t = NP.arange(-1., 1., 100)
s = NP.sin(NP.pi*x)
fig = PLT.figure()
ax1 = fig.add_subplot(111)
ax1.plot(t, s, 'b.')
buffer = StringIO.StringIO()
canvas = PLT.get_current_fig_manager().canvas
canvas.draw()
pil_image = PIL.Image.fromstring('RGB', canvas.get_width_height(),
canvas.tostring_rgb())
pil_image.save(buffer, 'PNG')
PLT.close()
# Django's HttpResponse reads the buffer and extracts the image
return HttpResponse(buffer.getvalue(), mimetype='image/png')
我有同样的问题,我偶然发现了这个答案。 只是想添加上面的答案, PIL.Image.fromstring
已被弃用,现在应该使用frombytes而不是fromstring。 因此,我们应该修改行:
pil_image = PIL.Image.fromstring('RGB', canvas.get_width_height(),
canvas.tostring_rgb())
至
pil_image = PIL.Image.frombytes('RGB', canvas.get_width_height(),
canvas.tostring_rgb())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.