如何临时存储生成的图像以供下载

How to temporary store a generated image for download

我已经编写了一些用于拍摄图像并向其中添加一些文本的代码。目前它只是在本地保存文件,但我希望它临时存储新生成的图像,所以当会话被 closed 时,文件被删除。另外,将来多个用户可以同时使用该功能,而无需一个用户写另一个图像。

我当前的代码是:

def Output(request):
    inputValue = request.GET.get('t', '')
    my_image = Image.open(os.path.join(BASE_DIR, 'media', 'blank.jpg'))
    title_font = ImageFont.truetype(os.path.join(BASE_DIR, 'homepage', 'static', 'homepage', 'Mistral.ttf'), 60)
    title_text = inputValue
    image_editable = ImageDraw.Draw(my_image)
    image_editable.text((45,333), title_text, (0, 0, 0), font=title_font)
    my_image.save(os.path.join(BASE_DIR, 'media', 'result.jpg'))
    return TemplateResponse(request, 'homepage/output.html', {'title': 'Output'})

所以 os 在本地将图像保存为 result.jpg,如何为特定会话临时保存它?

你可以使用base64的概念,将你的result.jpg转换成base64,然后通过context

传递base64字符串
import base64
from io import BytesIO
from PIL import Image

def get_base64(image):
    buffered = BytesIO()
    image.save(buffered, format="JPEG")
    img_str = base64.b64encode(buffered.getvalue())
    return "data:image/jpeg;base64," + img_str.decode()


def Output(request):
    inputValue = request.GET.get('t', '')
    my_image = Image.open(os.path.join(BASE_DIR, 'media', 'blank.jpg'))
    title_font = ImageFont.truetype(os.path.join(BASE_DIR, 'homepage', 'static', 'homepage', 'Mistral.ttf'), 60)
    title_text = inputValue
    image_editable = ImageDraw.Draw(my_image)
    image_editable.text((45,333), title_text, (0, 0, 0), font=title_font)
    base_image = get_base64(image_editable)
    return TemplateResponse(request, 'homepage/output.html', {'base_image': base_image})

在HTML文件中

<img src="{{base_image}}"/> 

因此您不需要在系统中保存图像,base64 图像将很容易地用于 HTML 图像标签

我通过修改 Neeraj Kumar 写的内容让它工作

import os
from django.shortcuts import render
from django.template.response import TemplateResponse
from PIL import Image, ImageFont, ImageDraw
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
from io import BytesIO
import base64

def get_base64(image):
    img = Image.open(image)
    buffered = BytesIO()
    img.save(buffered, format="PNG")
    img_str = base64.b64encode(buffered.getvalue())
    return img_str.decode()

def Output(request):
    inputValue = request.GET.get('t', '')
    my_image = Image.open(os.path.join(BASE_DIR, 'media', 'blank.png'))
    title_font = ImageFont.truetype(os.path.join(BASE_DIR, 'homepage', 'static', 'homepage', 'Mistral.ttf'), 60)
    title_text = inputValue
    image_editable = ImageDraw.Draw(my_image)
    image_editable.text((45,333), title_text, (0, 0, 0), font=title_font)
    my_image.save(os.path.join(BASE_DIR, 'media', 'result.png'))
    base_image = "data:image/png;base64," + get_base64(os.path.join(BASE_DIR, 'media', 'result.png'))
    return TemplateResponse(request, 'homepage/output.html', {'title': 'Output', 'base_image': base_image})