python - 如何使用PIL Image在Django网页中输出图像

标签 python django python-imaging-library

我使用 Image.new 在 django View 中创建一个图像对象, 我想在网页中显示它。

x = Image.new('RGB',(400,400)) 返回 HttpResponse(x.show(), mimetype="image/png")

不起作用。

如何将图像对象转换为图像原始二进制文件?

最佳答案

您可以将 Base64 图像嵌入 <img src=所以你可以尝试将 PIL 图像转换为 base64。

from PIL import Image
import StringIO

x = Image.new('RGB',(400,400))
output = StringIO.StringIO()
x.save(output, "PNG")
contents = output.getvalue().encode("base64")
output.close()
return HttpResponse('<img src="data:image/png;base64,' + contents + ' />')

关于python - 如何使用PIL Image在Django网页中输出图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12375393/

相关文章:

django - 渲染多对多字段

python - 加速截图功能 - Python

python - 在 Kivy Canvas 上显示 PIL 图片

Python 编辑/重命名 .json 中的键名

javascript - 如何通过 jinja[Flask] 访问外部 javascript 文件?

django - 使用 Nginx 和 Apache 的嵌入式设备的最佳快速身份验证机制

django - 使用 Django Rest 框架发布空日期字段错误

python - Image.fromarray 只产生黑色图像

python - 通过索引号引用字典元素

python - 如何在 Pandas 中找到两个数据集的对齐方式