【问题标题】:Return an image to the browser in python, cgi-bin在python,cgi-bin中将图像返回给浏览器
【发布时间】:2011-03-13 00:04:42
【问题描述】:

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

【问题讨论】:

  • 如果您发布代码,您将获得更好的响应。此外,如果您能描述正在发生的事情,而不仅仅是“这不起作用”,我们将获得更多线索。

标签: python image apache2 cgi-bin


【解决方案1】:
  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 响应需要回车、换行

【讨论】:

  • 是的,#3 就是它。感谢您的跟进。
  • @adamk 如果我想从脚本中执行某些东西然后执行它,它对我不起作用。假设我想创建一个文件然后关闭它。它返回图像,但文件没有在服务器上创建。任何输入? #!/usr/bin/env python import sys f = open('workfile', 'w') f.close() filename="th_goldhill.png" sys.stdout.write("Content-type: image/png\ r\n\r\n" + 文件(文件名,"rb").read() )
【解决方案2】:

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

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

【讨论】:

  • 如何确定all string characters reading correctly ? 。我尝试了这种方法百万次,但没有任何成功。您对print 功能有任何想法吗?版主在哪里?不要浪费用户的生命! -1
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-06-30
  • 2016-02-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-30
相关资源
最近更新 更多