打开图像文件,将其另存为字符串并将其转换为base64

问题描述 投票:0回答:1

我正在做一个Django项目,该项目需要接收图像并将其作为TextField存储到数据库中。为此,我正在做类似的事情:

在我的模型中。py:

class Template(models.Model):
    image = models.TextField(null=True, blank=True)

等效代码为:

with open('logo.png', 'wb') 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文件中。我也尝试过复制解码后的数据,并在另一个站点打开它,但文件损坏。

如何修复代码以正确转换图像?

python html django weasyprint
1个回答
0
投票

据我所知,您正在以写权限打开图像。

with open('logo.png', 'wb') as file:
    image = str(file.read())

尝试将'open()-函数'与'rb'一起使用。

请参见Python Docu Input and Output-“当仅读取文件时,模式可以为'r',仅写入时为'w'(将删除具有相同名称的现有文件)...”

尝试:

with open('logo.png', 'rb') as file:
    image = str(file.read())
© www.soinside.com 2019 - 2024. All rights reserved.