4

我正在尝试在 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.

4

2 回答 2

7
  1. 您可能需要打开文件"rb"(在基于 Windows 的环境中通常是这种情况。
  2. 简单的打印可能不起作用(因为它添加了 '\n' 和其他东西),最好write将它添加到sys.stdout.
  3. 该语句print "Content-type: image/png\n\n"实际上打印了 3 个换行符(因为 print 会在最后自动添加一个“\n”。这可能会破坏您的 PNG 文件。

尝试:

sys.stdout.write( "Content-type: image/png\r\n\r\n" + file(filename,"rb").read() )
  1. HTML 响应需要回车、换行
于 2010-07-07T19:26:30.323 回答
0

您是否在标题后包含空白行?如果没有,这不是标题的结束!

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

于 2010-07-07T19:28:29.933 回答