返回一个图像浏览器中的蟒蛇,cgi-bin目录 [英] Return an image to the browser in python, cgi-bin

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

问题描述

我试图建立在cgi-bin目录,简单地返回内容类型的标题一个python脚本:图像/ PNG并返回图像。我试着打开图像和打印f.read()返回,但运行不正常。

编辑:
在code我试图使用方法是:

 打印内容类型:image / PNG \\ n \\ n
开放(/ home / user中的/ tmp / image.png,R)为f:
    打印f.read()

这是使用Ubuntu 10.04服务器上的Apache。当我加载网页铬我得到的破碎的形象图片,当我加载页面在Firefox,我得到图像的 HTTP://localhost/cgi-bin/test.py 无法显示,因为它包含错误


解决方案

  1. 您可能需要打开该文件作为根据环境它通常的情况下RB(在Windows中。

  2. 只需打印可能无法正常工作(因为它增加的'\\ n'之类的东西),更好的只是为sys.stderr

  3. 语句打印内容类型:image / PNG \\ n \\ n实际打印3换行符(如打印自动添加在最后一\\ n。这可能会打破你的PNG文件。

尝试:

  sys.stdout.write函数(内容类型:image / PNG \\ r \\ n \\ r \\ n+文件(文件名,RB),读())


  1. HTML响应需要回车,换行

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.

EDIT: the code I'm trying to use is:

print "Content-type: image/png\n\n"
with open("/home/user/tmp/image.png", "r") as f:
    print f.read()

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. 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.

Try:

sys.stdout.write( "Content-type: image/png\r\n\r\n" + file(filename,"rb").read() )

  1. HTML responses require carriage-return, new-line

这篇关于返回一个图像浏览器中的蟒蛇,cgi-bin目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆