【发布时间】:2010-10-15 00:45:33
【问题描述】:
嗨,我是否可以从 matplotlib 创建图像并将其保存在从 PIL 创建的图像对象上?听起来很难吗?谁能帮帮我?
【问题讨论】:
标签: python image matplotlib python-imaging-library
嗨,我是否可以从 matplotlib 创建图像并将其保存在从 PIL 创建的图像对象上?听起来很难吗?谁能帮帮我?
【问题讨论】:
标签: python image matplotlib python-imaging-library
在 Django 框架的网页中渲染 Matplotlib 图像:
创建 matplotlib 图
将其保存为 png 文件
将此图像存储在字符串缓冲区中(使用 PIL)
将此缓冲区传递给 Django 的 HttpResponse(设置 mime 类型 image/png)
返回一个响应对象(在本例中为渲染图)。
换句话说,所有这些步骤都应该放在一个 Django view 函数中,在 views.py 中:
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.frombytes(
'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())
【讨论】: