提问者:小点点

带有Django和matplotlib的透明PNG


我目前有一个Django项目,具有查看功能,代码如下(代码复制自本文):

from pylab import figure, axes, pie, title
from matplotlib.backends.backend_agg import FigureCanvasAgg

def test_matplotlib(request):
    f = figure(1, figsize=(6,6))
    ax = axes([0.1, 0.1, 0.8, 0.8])
    labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
    fracs = [15,30,45, 10]
    explode=(0, 0.05, 0, 0)
    pie(fracs, explode=explode, labels=labels, autopct='%1.1f%%', shadow=True)
    title('Raining Hogs and Dogs', bbox={'facecolor':'0.8', 'pad':5})

    canvas = FigureCanvasAgg(f)    
    response = HttpResponse(content_type='image/png')
    canvas.print_png(response)
    return response

它从一个图创建一个png并直接提供服务。如何在这个png中使图形的背景透明?


共1个答案

匿名用户

未经测试,但这应该有效。您不必写入(实际的)文件,类似文件的对象应该可以工作。此代码将图像保存到响应中。

def test_matplotlib(request):
    f = figure(1, figsize=(6,6))
    ax = axes([0.1, 0.1, 0.8, 0.8])
    labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
    fracs = [15,30,45, 10]
    explode=(0, 0.05, 0, 0)
    pie(fracs, explode=explode, labels=labels, autopct='%1.1f%%', shadow=True)
    title('Raining Hogs and Dogs', bbox={'facecolor':'0.8', 'pad':5})

    #canvas = FigureCanvasAgg(f)    
    response = HttpResponse(content_type='image/png')
    f.savefig(response, transparent=True, format='png')
    #canvas.print_png(response)
    return response