0

我在读取图像文件(.png、.jpg、.jpeg ...)时遇到问题,在终端中出现以下错误: UnicodeDecodeError: the 'utf-8' codec cannot decode the 0x89 byte in position 0 : invalid起始字节。我以为我已经通过声明 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正常打开的文件的预览:

在此处输入图像描述

4

1 回答 1

1

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

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

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

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]
于 2021-03-02T13:12:25.527 回答