use*_*652 14 python image matplotlib python-imaging-library
HI,我是否有可能从matplotlib创建一个图像并将其保存在我从PIL创建的图像对象上?听起来很难?谁能帮我?
dou*_*oug 16
要在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')
Run Code Online (Sandbox Code Playgroud)
我当时有同样的问题,但我偶然发现了这个答案。只是想添加到上面PIL.Image.fromstring
已经弃用的答案中,现在应该使用frombytes代替fromstring。因此,我们应该修改以下行:
pil_image = PIL.Image.fromstring('RGB', canvas.get_width_height(),
canvas.tostring_rgb())
Run Code Online (Sandbox Code Playgroud)
至
pil_image = PIL.Image.frombytes('RGB', canvas.get_width_height(),
canvas.tostring_rgb())
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
8572 次 |
最近记录: |