Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/342.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python在PIL图像对象上保存matplotlib图形_Python_Image_Matplotlib_Python Imaging Library - Fatal编程技术网

Python在PIL图像对象上保存matplotlib图形

Python在PIL图像对象上保存matplotlib图形,python,image,matplotlib,python-imaging-library,Python,Image,Matplotlib,Python Imaging Library,您好,我是否可能从matplotlib创建了一个图像,并将其保存在从PIL创建的图像对象上?听起来很难?谁能帮助我?要在Django框架中的网页中呈现Matplotlib图像,请执行以下操作: 创建matplotlib绘图 将其另存为png文件 将此图像存储在字符串缓冲区中(使用PIL) 将此缓冲区传递给Django的HttpResponse(设置mime类型image/png) 它返回一个响应对象(本例中为渲染图)。 换句话说,所有这些步骤都应该放在Django view函数中的views

您好,我是否可能从matplotlib创建了一个图像,并将其保存在从PIL创建的图像对象上?听起来很难?谁能帮助我?

要在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.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())