簡體   English   中英

Python在PIL Image對象上保存matplotlib圖

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

HI,我是否有可能從matplotlib創建一個圖像並將其保存在我從PIL創建的圖像對象上? 聽起來很難? 誰能幫我?

要在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')

我有同樣的問題,我偶然發現了這個答案。 只是想添加上面的答案, 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())

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM