我在读取图像文件(.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正常打开的文件的预览: