【发布时间】:2020-09-25 00:40:25
【问题描述】:
我正在做一个 Django 项目,该项目需要接收图像并将其作为 TextField 存储到数据库中。为了实现这一点,我正在做类似的事情:
在我的models.py中:
class Template(models.Model):
image = models.TextField(null=True, blank=True)
等效代码为:
with open('logo.png', 'rb') as file:
image = str(file.read())
Template.objects.create(id=1, image=image)
稍后,当我需要取回文件并将其转换为 base64 以插入 HTML 文件时,我正在执行以下操作:
import base64
from django.template import Template as DjangoTemplate
from django.template import Context
from weasyprint import HTML
from .models import Template
template = Template.objects.get(id=1)
data = {'logo': base64.b64encode(str.encode(template.image)).decode('utf-8')}
html_template = DjangoTemplate(template.html_code)
html_content = html_template.render(Context(data)))
file = open('my_file.pdf', 'wb')
file.write(HTML(string=html_content, encoding='utf8').write_pdf())
file.close()
但问题是图像没有显示在 pdf 文件中。我也尝试复制解码后的数据并用另一个站点打开它,但我得到了一个损坏的文件。
如何修复我的代码以正确转换图像?
【问题讨论】:
-
我不确定这是否有帮助,但我个人会将数据作为 base64 字符串存储在您的模型中。像这样stackoverflow.com/questions/4915397/django-blob-model-field.
-
这确实有效,但我发现存储 base64 不是一个好习惯,而且存储成本更高。 stackoverflow.com/questions/11402329/…
-
是的,它会更大。但是,如果您尝试将二进制数据插入文本字段,则二进制数据将被重新解释为使用的字符串编码。如果以 utf-8 为例,根据字节的值,1 到 4 个字节将被转换为一个字符。 en.m.wikipedia.org/wiki/….
-
你这是什么意思?这就是我以后无法将文件转换为 base64 的原因吗?
-
这可能是原因。检查输入图像二进制缓冲区的大小和 template.image 输出。它们的大小可能不同。那是因为字符串编码。
标签: python html django weasyprint