【问题标题】:Django / Python - Convert image from AWS S3 bucket to Base64?Django / Python - 将图像从 AWS S3 存储桶转换为 Base64?
【发布时间】:2020-10-01 13:56:21
【问题描述】:

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

views.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_plain.html

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

【问题讨论】:

    标签: python html django amazon-s3 base64


    【解决方案1】:

    问题在于 context['recipe_image_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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-11
      • 1970-01-01
      • 2023-03-29
      相关资源
      最近更新 更多