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



我已经编写了一些代码来获取图像,并向其添加一些文本。目前它只是将文件保存在本地,但我希望它将新生成的图像临时存储,因此当会话关闭时,文件将被删除。此外,在未来,多个用户将能够同时使用该功能,而无需一个用户重写另一个用户的图像。

我当前的代码是:

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'})

所以,而不是保存图像本地为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})

相关内容

  • 没有找到相关文章

最新更新