Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to encode image to send over Python HTTP server?

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)

like image 803
Thomas Wagenaar Avatar asked Feb 17 '15 17:02

Thomas Wagenaar


1 Answers

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()
like image 54
Juergen Avatar answered Oct 23 '22 01:10

Juergen