在python中将图像返回给浏览器,cgi-bin
我正在尝试在cgi-bin中设置一个Python脚本,这个脚本的功能很简单,就是返回一个内容类型为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中加载时,我看到的错误信息是无法显示图片 http://localhost/cgi-bin/test.py,因为它包含错误。
2 个回答
0
你有没有在标题后面加一个空行?如果没有,那就说明你的标题还没结束呢!print 'Content-type: image/png'
print
print f.read()
7
- 你可能需要以
"rb"
的方式打开文件(在Windows环境下通常是这样)。 - 直接打印可能不太好用(因为它会加上'\n'等东西),最好是直接用
write
方法把内容写到sys.stdout
。 - 这句
print "Content-type: image/png\n\n"
实际上会打印出三个换行符(因为print会自动在最后加一个"\n")。这可能会导致你的PNG文件出错。
试试:
sys.stdout.write( "Content-type: image/png\r\n\r\n" + file(filename,"rb").read() )
- HTML响应需要回车和换行。