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

标签 image http python-3.x server encode

我需要一些关于我的以下处理程序的帮助:

 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:如果我连接到我的 http 服务器,我希望在浏览器中看到发送的图像)

最佳答案

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

可以找到其他内容类型 here .

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

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

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

对于二进制数据你可以这样使用:

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

关于image - 如何编码图像以通过 Python HTTP 服务器发送?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28567733/

相关文章:

javascript - 如何在鼠标悬停时交换图像并在鼠标移出时交换回原始图像?

html - GET 请求中的 "example.com"指的是什么?

python - 我将图片转换为 GIF 但 turtle 的 bgpic() 仍然无法正常工作

javascript - 如何在 Node.js 中将 base64 解码为图像文件?

python - 使用 PIL 获取像素的 RGB

python - 禁用 python 内置函数

python - 遍历字典列表并与其他字典进行比较

javascript - 在什么情况下发出 HTTP 请求但未收到响应?

c - 通过 HTTP 接收数据 - 大小不一致

python - 将元组列表格式化为小数并将它们添加到文件中