简体   繁体   中英

Django / Python - Convert image from AWS S3 bucket to Base64?

I'm trying to convert each image instance to base64 using images URL. All images are stored in my amazon-s3 bucket. Unfortunately, my generated encryption is not displaying the image at my recipe_plain.html template. Any help is appreciated.

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 }}">

The issue was that context['recipe_image_base64'] variable was returning the base64 in bytes object. This has been resolved using the decode() function.

I also simplified the script using the requests library and included a validation.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM