如何将生成的 PIL 映像从 Django REST 框架后端获取到前端?

我计划制作一个Web应用程序,我可以在其中发出POST请求,以在后端使用PIL生成图像,并通过GET通过REST框架将其链接到前端,我可以在其中下载它。我不想将生成的图像保存在数据库中。只想生成一次仅用于下载。关于我如何实现它的任何想法?


肥皂起泡泡
浏览 141回答 2
2回答

繁星coding

我找到了一种方法来生成图像,而无需将其保存在文件夹中。您基本上将图像保存为字节并转换为base64。views.pyimport ioimport base64from PIL import Imagefrom django.shortcuts import renderfrom django.utils.safestring import mark_safedef home(request):&nbsp; im_io = io.BytesIO()&nbsp; im = Image.new('RGBA', (300,300), (255, 214, 107))&nbsp; im_bg.text((10,0), test, fill='black')&nbsp; im.save(im_io, 'png', quality=70)&nbsp; im_io.seek(0)&nbsp; im_io_png = base64.b64encode(im_io.getvalue())&nbsp; context = im_io_png.decode('UTF-8')&nbsp; img_tag = mark_safe(f"<img src='data:image/png;base64, {context}'/>")&nbsp; return render(request, 'home.html', {'img_tag': img_tag })家.html<body>&nbsp; <h1>The Poster Generator </h1>&nbsp; <div>{{img_tag}}</div> <!-- Image will display here --></body>

月关宝盒

您可能希望使用StreamingHttpResponse,它允许您发送FileField(或ImageField,就此而言)作为http响应。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python