通过 HTTP 提供图像时图像损坏

Broken image when serving it over HTTP

我在读取图像文件(.png、.jpg、.jpeg ...)时遇到问题,我在终端中收到以下错误:UnicodeDecodeError:'utf-8' 编解码器无法解码 0x89 字节在位置 0:无效的起始字节。我以为我只是通过声明 o_file = open ("cloud.png", "rb") 就解决了这个问题,因为我不再在终端中收到错误,而是在查看文件时出错 (cloud.png) 根据下面的例子:

from wsgiref.simple_server import make_server

def hello_world_app(environ, start_response):

    i_file = open("cloud.png", "rb")
    o_file = i_file.read()

    status = '200 OK'  # HTTP Status
    headers = [("Content-type", "image/png; charset=utf-8")]
    start_response(status, headers)

    # The returned object is going to be printed
    return [str(o_file).encode("utf-8")]

with make_server('', 8000, hello_world_app) as httpd:

    print(
        'Running Kosmos Application\n'
        'Browser Access - http://127.0.0.1:8000\n'
        'Crl+c for flow command or Crl+z for stop'
    )
    # Serve until process is killed
    httpd.serve_forever()

我想知道为什么会出现这种情况,如何在不使用第三方模块的情况下解决这个问题?下面是在不使用 python:

的情况下正常打开的文件的预览

您似乎对字符编码的用途感到非常困惑。

在尝试阅读此答案的其余部分之前,可能先阅读 Joel Spolsky 的 The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)

当您 encode 时,您正在用 mojibake 替换二进制 PNG 数据。您根本不应该操纵数据;只需将其读入缓冲区,然后将其发送给客户端即可。故事结束。

def hello_world_app(environ, start_response):
    with open("cloud.png", "rb") as i_file:
        o_file = i_file.read()

    status = '200 OK'  # HTTP Status
    headers = [("Content-type", "image/png")]  # no ; charset here!
    start_response(status, headers)

    return [o_file]