簡體   English   中英

將圖像返回到python,cgi-bin中的瀏覽器

[英]Return an image to the browser in python, cgi-bin

我正在嘗試在cgi-bin中設置一個python腳本,它只返回一個帶有content-type:image / png的頭文件並返回圖像。 我嘗試打開圖像並使用print f.read()返回它,但這不起作用。

編輯:我正在嘗試使用的代碼是:

print "Content-type: image/png\n\n"
with open("/home/user/tmp/image.png", "r") as f:
    print f.read()

這是在ubuntu服務器10.04上使用apache。 當我在chrome中加載頁面時,我得到了損壞的圖像圖像,當我在firefox中加載頁面時,我得到The image http://localhost/cgi-bin/test.py" cannot be displayed, because it contains errors.

  1. 您可能需要將文件打開為"rb" (在基於Windows的環境中,通常就是這種情況。
  2. 簡單的打印可能不起作用(因為它添加'\\ n'和東西),更好的只是writewrite sys.stdout
  3. 聲明print "Content-type: image/png\\n\\n"實際打印3個換行符(因為打印自動添加一個“\\ n”到最后。這可能會破壞您的PNG文件。

嘗試:

sys.stdout.write( "Content-type: image/png\r\n\r\n" + file(filename,"rb").read() )
  1. HTML響應需要回車,換行

你是否在標題后面加上空白行? 如果沒有,它不是你的標題的結尾!

print 'Content-type: image/png'
print
print f.read()

暫無
暫無

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

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