Send ImageField Attribute Images in Model by JsonResponse

I send images through JsonResponse to clients but the problem is the encoding of the images
the client cannot display them because of the encoding in

This is how I sends the images:

            data = [
            {'certificate': str(base64.b64encode(rubro.first(),
            'picture1': str(base64.b64encode(rubro.first(),
            'picture2': str(base64.b64encode(rubro.first(),
            'picture3': str(base64.b64encode(rubro.first()},]

            return JsonResponse(data, safe=False)

If I try to directly send the ImageField like this:

            data = [
            {'certificate': rubro.first().certificate,
            'picture1': rubro.first().picture1,
            'picture2': rubro.first().picture1,
            'picture3': rubro.first().picture1},]

            return JsonResponse(data, safe=False)

I get: TypeError: Object of type ImageFieldFile is not JSON serializable

What I must do? How Can I send imagen from ImageField to clients?

Can you explain why the first case in which you read the image into a base64 encoded string is unacceptable? I think I’m missing some context for your question and understanding that may help.

The client is responsible for decoding the image and displaying it as a picture in the browser.

Also, please don’t keep adding new topics for this same issue - it’s a lot better to continue the previous thread, providing context for those reading it without you having to duplicate information posted in other threads.

This is now the third thread on this topic - if you’re interested in following along, start with reviewing the previous two threads.

1 Like

The problem of this topic is different

Because if I send the following, it gives me a wrong encoding of the image


I can’t send the following


because I get:

TypeError: Object of type bytes is not JSON serializable

It’s still the same thread - you’re trying to send images from the server to the client - they’re all related issues.

But I don’t know what you mean by it giving you the “wrong encoding” of the image. That should give you the base64-encoded version of your image.

The JavaScript in the client is responsible for decoding that base64-encoded data back to the binary image to be added to the page.

1 Like

because I must convert the base64-encode image to str to be able to sends it

If I set what server sends to this decode I get an error: Best Online Base64 to Image Decoder / Converter

So the base64-encode is not good

See the docs for the bytes.decode method for converting a bytes object to a Python string.

You may also find it useful to review the Python docs on Unicode, Bytes, and Strings to get a better understanding of the relationships between Python strings and byte objects.