【问题标题】:Django dynamically created temporary image not displayingDjango动态创建的临时图像不显示
【发布时间】:2021-11-17 08:07:33
【问题描述】:

我想根据用户输入动态创建图像并将其显示给用户。

views.py:

class TreatmentTemplateView(TemplateView):
    template_name = "../templates/patient/treatment_detail.html"

    def get_context_data(self, *args, **kwargs):
        context = super().get_context_data(*args, **kwargs)
        context["patient_id"] = self.kwargs["patient_id"]
        result = find_treatment(context["patient_id"])
        context = result[0]
        context["patient"] = result[1]
        context['image'] = result[2]
        print(context['image'])
        return context

图片是在find_treatment(context["patient_id”])生成的 通过find_treatment的子功能

fig = sns_plot.get_figure()
img_in_memory = BytesIO()
fig.savefig(img_in_memory, format="png") #dunno if your library can do that.
image = base64.b64encode(img_in_memory.getvalue())

模板包含:

<img src="data:image/png;base64,{{image}}" />

但是图像没有显示,这是我在模板中引用图像的方式的问题吗?

【问题讨论】:

    标签: python django django-views temporary-files


    【解决方案1】:

    base64.b64encode 可能返回一个字节字符串。要转换为字符串,您可以使用 django 设置文件中定义的 DEFAULT_CHARSET 或“UTF-8”。

    from django.conf import settings
    
    
    image = image.decode(settings.DEFAULT_CHARSET)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-05
      • 1970-01-01
      • 2017-11-27
      • 1970-01-01
      • 2016-07-08
      • 2017-04-04
      • 2020-02-17
      • 1970-01-01
      相关资源
      最近更新 更多