如何编码图像以通过 Python HTTP 服务器发送?

How to encode image to send over Python HTTP server?

我需要以下处理程序的帮助:

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

我知道了,函数 load() 是文件中的其他人。通过我的 HTTP 处理程序发送 HTML 页面似乎可以正常工作,但我该如何发送图像?我需要如何对其进行编码以及我应该使用什么 Content-type

非常感谢帮助!

(PS:如果我连接到我的 httpserver,我希望发送的图像能在浏览器中看到)

对于 PNG 图像,您必须将内容类型设置为“image/png”。对于 jpg:“image/jpeg”。

可以找到其他内容类型 here

编辑:是的,我在第一次编辑时忘记了编码。

答案是:你不知道!当您从文件加载图像时,它已经采用了正确的编码。

我读到了你的编解码器问题:问题是,正如我在你的加载函数中看到的那样。不要尝试对文件内容进行编码。

您可以使用二进制数据:

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

如 Juergen 所述,您必须设置相应的内容类型。 我找到的这个例子可能对你有帮助:https://github.com/tanzilli/playground/blob/master/python/httpserver/example2.py

示例在Python2中,但改动应该很小。

啊,最好使用 self 而不是 client -> 请参阅 PEP 8、Python 的风格指南