简体   繁体   English

Python在PIL Image对象上保存matplotlib图

[英]Python save matplotlib figure on an PIL Image object

HI, is it possible that I created a image from matplotlib and I save it on an image object I created from PIL? HI,我是否有可能从matplotlib创建一个图像并将其保存在我从PIL创建的图像对象上? Sounds very hard? 听起来很难? Who can help me? 谁能帮我?

To render Matplotlib images in a webpage in the Django Framework: 要在Django Framework的网页中呈现Matplotlib图像:

  • create the matplotlib plot 创建matplotlib图

  • save it as a png file 将其保存为png文件

  • store this image in a string buffer (using PIL) 将此图像存储在字符串缓冲区中(使用PIL)

  • pass this buffer to Django's HttpResponse (set mime type image/png) 将此缓冲区传递给Django的HttpResponse (设置mime类型图像/ png)

  • which returns a response object (the rendered plot in this case). 它返回一个响应对象 (在这种情况下为渲染图)。

In other words, all of these steps should be placed in a Django view function, in views.py : 换句话说,所有这些步骤都应放在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')

I was having the same question and I stumbled upon this answer. 我有同样的问题,我偶然发现了这个答案。 Just wanted to add to the above answer that PIL.Image.fromstring has been deprecated and frombytes should be used now instead of fromstring. 只是想添加上面的答案, PIL.Image.fromstring已被弃用,现在应该使用frombytes而不是fromstring。 Hence, we should modify line: 因此,我们应该修改行:

pil_image = PIL.Image.fromstring('RGB', canvas.get_width_height(), 
                 canvas.tostring_rgb())

to

pil_image = PIL.Image.frombytes('RGB', canvas.get_width_height(), 
                 canvas.tostring_rgb())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM