Jay Cee Jay Cee - 3 months ago 8
Python Question

Python encode an image in base 64 after a html upload

I have an input for images upload in my page.
When you click on "send image" the post request is received in my back-end.

I don't, and I don't want to, save the image.

What I do, from the back, is: I send the image to an API which will return me the image's tags and then I will display the tags and the image itself, that has been uploaded, in my html page.

if request.method == "POST":
form = ImageForm(request.POST, request.FILES)

if form.is_valid():
imageUploaded = request.FILES['image_file']
try:
c = Client(cId, sId)
c.get_token()
tags = c.image_lookup(imageUploaded)

urlImage = base64.b64encode(imageUploaded.read())
context.update({
'image_path': urlImage,
'tags': tags.json,
'btn_visible': True,
})
except ValueError as e:
logging.info(e)
context.update({
'btn_visible': False,
'error_message': 'A problem occured, we will fix it as soon as possible. We apologise for the inconvenience.'
})


in my HTML:

<img id="cv-image" src="data:image/png;base64,{{ image_path }}">


But, my problem is that my image_path is desperately empty.

What's the problem?

EDIT:
It's super weird, if I comment the code calling the Client class, which do a GET and a POST on an API, it will works. I still don't get it nor how to make it works.

Answer

Ok, as I'm not saving the image, once I send it to the API the object in itself isn't available anymore.

Not sure to understand why I still can print it, I had to make a copy of it:

if form.is_valid():
            imageUploaded = request.FILES['image_file']
            imageCopy = copy.deepcopy(imageUploaded)
            try:
                c = Client(cId, sId)
                c.get_token()
                tags = c.image_lookup(imageUploaded)

                urlImage = base64.b64encode(imageCopy.read())

And now it works perfectly fine!

As asked, here is the code of Image_lookup:

def image_lookup(self, imageUploaded, image_type=None):
        '''POST /v1/imageLookup'''
        param_files = [
            ('input_image', ('image.jpg', imageUploaded, image_type or 'image/png'))
        ]

        return self.post('someAPIurl/imageLookup', files=param_files)
Comments