使用 python 3 将图像写入网页

Write image to webpage with python 3

我目前已设置此代码:

    import time
    import http.server
    import socketserver
    import mimetypes
    import os

    HOST_NAME = 'localhost'
    PORT = 8000


    def load(self):
        with open(self, 'r') as self:
        self = self.read()
        return self.encode('UTF-8')



    class MyHandler(http.server.BaseHTTPRequestHandler):
        def do_HEAD(self):
            self.send_response(200)
            self.send_header("Content-type", "text/html")
            self.end_headers()
            def do_GET(self):
                    if self.path == "/":
                        self.send_response(200)
                        self.send_header("Content-type", "text/html")
                        self.end_headers()
                        self.wfile.write(load('index.html'))
                    if self.path.endswith('.css'):
                        self.send_response(200)
                        self.send_header("Content-type", "text/css")
                        self.end_headers()
                        dest = self.path.replace("/", "")
                        self.wfile.write(load(dest))
                    if self.path == "/bg.jpg":
                        self.send_response(200)
                        self.send_header("Content-type", "image/jpeg")
                        self.end_headers()

    if __name__ == '__main__':
        httpd = socketserver.TCPServer(("", PORT), MyHandler)
        print(time.asctime(), "Server Starts - %s:%s" % ("", PORT))
        try:
            httpd.serve_forever()
        except KeyboardInterrupt:
            pass
        httpd.server_close()
        print(time.asctime(), "Server Stops - %s:%s" % ("", PORT))

我的网页似乎可以正常工作,当我打开我的网页时,我的 index.html 和 css 已加载,但是图像无法显示,有人知道为什么吗?

要通过 HTTP 发送图像,只需将图像数据直接写入套接字,就像任何其他类型的文件一样。您不能为此使用 load() 函数,因为它将文本编码为 UTF-8。相反,您应该使用 rb 或类似模式打开文件,从该文件句柄中读取 bytes,然后将其直接写入 HTTP 处理程序中的 self.wfile