首页 > 解决方案 > 如何显示使用 PIL 操作的上传图像而不保存到文件 Django

问题描述

我从数据库中提取图像用作背景,并使用 PIL 将用户上传的图像放置在背景之上。我想在转换完成后将此图像显示到 html 页面而不保存到文件系统。我看过很多类似的问题,但我在这里做了一些不同的事情。我试图根据其他答案制作一些代码,但在用户提交照片后,我无法让图像显示在屏幕上。我怎样才能让它工作?这是我的代码:

from django.core.files.storage import FileSystemStorage
from PIL import Image
from io import BytesIO
import base64
import io
from .models import Samplecards

def imageUpload(request):
    if request.method == 'POST':
        selection = request.POST['selection']
        sample = getImage()
        theImage = io.BytesIO(sample.image)
        print("DONE")

        uploaded_image = request.FILES['img']

        foreground = Image.open(uploaded_image).convert("RGBA")
        background = Image.open(theImage).convert("RGBA")

        background.paste(foreground, (440, 190), foreground)
        buffered = BytesIO()
        background.save(buffered, format="png")
        b64_img = base64.b64encode(buffered.getvalue())

    return render(request, 'uploadpage.html', {"image": b64_img})

def getImage():
    img = Samplecards.objects.get(image_id=1)
    return img

在我的 html 文件中,我尝试像这样显示图像:

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

标签: pythondjango

解决方案


推荐阅读