Python将matplotlib图保存在PIL Image对象上 [英] Python save matplotlib figure on an PIL Image object
问题描述
我是否可以从matplotlib创建图像并将其保存在从PIL创建的图像对象上?听起来很难吗?谁可以帮助我?
is it possible that I created a image from matplotlib and I save it on an image object I created from PIL? Sounds very hard? Who can help me?
推荐答案
要在Django框架的网页中呈现Matplotlib图像,请执行以下操作:
To render Matplotlib images in a webpage in the Django Framework:
-
创建matplotlib图
create the matplotlib plot
将其另存为png文件
将此图像存储在字符串缓冲区中(使用PIL)
store this image in a string buffer (using PIL)
将此缓冲区传递给Django的 HttpResponse (设置为 mime类型 image/png)
pass this buffer to Django's HttpResponse (set mime type image/png)
返回一个响应对象(在这种情况下为渲染图).
which returns a response object (the rendered plot in this case).
换句话说,所有这些步骤都应放在Django view 函数的 views.py 中:
In other words, all of these steps should be placed in a Django view function, in 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.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')
这篇关于Python将matplotlib图保存在PIL Image对象上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!