簡體   English   中英

通過 HTTP 提供圖像時圖像損壞

[英]Broken image when serving it over HTTP

我在讀取圖像文件(.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 的情況下正常打開的文件的預覽:

在此處輸入圖像描述

您似乎對字符編碼的用途感到非常困惑。

在您嘗試閱讀此答案的 rest 之前,可能要閱讀 Joel Spolsky 的The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)

encode時,您將二進制 PNG 數據替換為mojibake 您根本不應該操縱數據; 只需將其讀入緩沖區,然后將其發送給客戶端。 故事結局。

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]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM