我的 mysql 数据库的 blob 字段中有一个图像。使用基本客户端可以正确显示图像,但我无法在 html 页面中显示图像。
我尝试对返回的字节使用 base64 转换器。
模型.py:
class BlobImg(models.Model):
photo = models.TextField(null=True)
views.py:
def home(request):
obj = BlobImg.objects.get(id=1)
image_data = base64.b64encode(obj.photo)
data = {
'news': News.objects.all(),
'title': 'Главная страница',
'imgs' : image_data
}
return render(request, 'app/home.html', data)
html:
<img src="data:image/jpeg;base64,{{ imgs }}" class="img-thumbnail">
我在“imgs”中得到字节串,但它不起作用
最佳答案
在 Python 3 中,base64.b64encode()
函数返回编码字节,而不是字符串。因此,您的数据 URI 显示为 data:image/jpeg;base64,b'/9j/4AA...'
,而它必须是 data:image/jpeg;base64 ,/9j/4AA...
。要解决此问题,请将字节解码为字符串,例如使用 base64.b64encode(obj.photo).decode()
。
关于python - 如何在 Django 的 HTML 页面上显示 blob 图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56138525/