How to encode image to send over Python HTTP server?

encode, http, image, python-3.x, server

Solution

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()

Problem

I would like some help on my following handler: ``` class MyHandler(http.server.BaseHTTPRequestHandler): def do_HEAD(client): client.send_response(200) client.send_header("Content-type", "text/html") client.end_headers() def do_GET(client): if client.path == "/": client.send_response(200) client.send_header("Content-type", "text/html") client.end_headers() client.wfile.write(load('index.html')) def load(file): with open(file, 'r') as file: return encode(str(file.read())) def encode(file): return bytes(file, 'UTF-8') ``` I've got this, the function `load()` is someone else in the file. Sending a HTML page over my HTTP handler seems to be working, but how can I send an image? How do I need to encode it and what `Content-type` should I use? Help is greatly appreciated! (PS: I would like the image that is send to be seen in the browser if I connect to my httpserver)

Original source