本文介绍了在python中将图像返回给浏览器,cgi-bin的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 cgi-bin 中设置一个 python 脚本,它只返回一个带有 content-type: image/png 的标题并返回图像.我试过打开图像并使用 print f.read() 返回它,但这不起作用.

I'm trying to set up a python script in cgi-bin that simply returns a header with content-type: image/png and returns the image. I've tried opening the image and returning it with print f.read() but that isn't working.

我尝试使用的代码是:

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" 无法显示,因为它包含错误.

This is using apache on ubuntu server 10.04. When I load the page in chrome I get the broken image image, and when I load the page in firefox I get The image http://localhost/cgi-bin/test.py" cannot be displayed, because it contains errors.

推荐答案

  1. 您可能需要以 "rb" 格式打开文件(在基于 Windows 的环境中通常是这种情况.
  2. 简单的打印可能不起作用(因为它添加了 '\n' 和其他东西),最好只是将它writesys.stdout.
  3. 语句 print "Content-type: image/png\n\n" 实际上打印了 3 个换行符(因为 print 会在末尾自动添加一个\n".这可能会破坏您的 PNG 文件.
  1. You may need to open the file as "rb" (in windows based environments it's usually the case.
  2. Simply printing may not work (as it adds '\n' and stuff), better just write it to sys.stdout.
  3. The statement print "Content-type: image/png\n\n" actually prints 3 newlines (as print automatically adds one "\n" in the end. This may break your PNG file.

试试:

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

这篇关于在python中将图像返回给浏览器,cgi-bin的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 06:18
查看更多