将图像返回到python,cgi-bin中的浏览器

ibo*_*eno 4 python image apache2 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()
Run Code Online (Sandbox Code Playgroud)

这是在ubuntu服务器10.04上使用apache.当我在chrome中加载页面时,我得到了破碎的图像图像,当我在firefox中加载页面时,我得到了The image http://localhost/cgi-bin/test.py" cannot be displayed, because it contains errors.

ada*_*amk 6

  1. 您可能需要打开文件"rb"(在基于Windows的环境中通常就是这种情况).
  2. 简单的打印可能不起作用(因为它添加'\n'和东西),更好的只是writesys.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() )
Run Code Online (Sandbox Code Playgroud)
  1. HTML响应需要回车,换行