Django/Python是否将图像从AWS S3存储桶转换为Base64?

2024-03-28 18:27:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用图像URL将每个图像实例转换为base64。所有图像都存储在我的amazon-s3存储桶中。不幸的是,我生成的加密没有在我的recipe_plain.html模板上显示图像。感谢您的帮助

视图.py

...
import base64

class RecipePlainView(DetailView):
    model = Recipe
    template_name = 'recipes/recipe_plain.html'

    def get_context_data(self, **kwargs):
        context = super(RecipePlainView, self).get_context_data(**kwargs)
        image = self.object.image
        image.open(mode='rb')
        context['recipe_image_base64'] = base64.b64encode(image.read())
        image.close()
        return context

recipe\u plain.html

<img src="data:image;base64,{{ recipe_image_base64 }}" alt="{{ recipe.image.name }}">

Tags: 实例name图像imageselfurldataget
1条回答
网友
1楼 · 发布于 2024-03-28 18:27:58

问题是context['recipe\u image\u base64']变量正在返回base64字节对象。这已使用decode()函数解决

我还使用requests库简化了脚本,并包含了一个验证

import base64, requests

class RecipePlainView(DetailView):
    model = Recipe
    template_name = 'recipes/recipe_plain.html'

    def get_context_data(self, **kwargs):
        url = self.object.image.url
        r = requests.get(url)
        if r.status_code == 200:
            byteBase64 = base64.b64encode(requests.get(url).content)
            context['recipe_image_base64'] = byteBase64.decode("utf-8")
        else:
            context['recipe_image_base64'] = False

        return context

相关问题 更多 >