How to encode image to send over Python HTTP server? How to encode image to send over Python HTTP server? python-3.x python-3.x

How to encode image to send over Python HTTP server?


For a PNG image you have to set the content-type to "image/png". For jpg: "image/jpeg".

Other Content types can be found here.

Edit: Yes, I forgot about encoding in my first edit.

The answer is: You don't! When you load your image from a file, it is in the correct encoding already.

I read about your codec problem: The problem is, as much I see in your load function. Don't try to encode the file content.

You may use for binary data this:

def load_binary(filename):    with open(filename, 'rb') as file_handle:        return file_handle.read()


As mentioned by Juergen you have to set the accordingly content-type.This example I found may help you: https://github.com/tanzilli/playground/blob/master/python/httpserver/example2.py

The example is in Python 2, but the changes should be minor.

Ah and it's better to use self instead of client -> see PEP 8, Python's style guide