python - 使用 Python 通过 http 输出图像时出现问题

标签 python

当通过 cgi 在我的网络服务器上访问脚本时,我正在尝试从我的本地磁盘加载一个图像文件并通过 http 输出它。

例如我想要http://example.com/getimage.py?imageid=foo返回相应的图像。然而,仅仅打开文件并在适当的内容标题之后打印 imgfile.read() 会导致图像被打乱。显然输出不正确,但我不知道为什么。

使用 2.6 的内置模块,最好的方法是什么?

编辑:

代码基本上可以归结为:

imgFile=open(fileName,"rb")
print "Content-type: image/jpeg"
print
print imgFile.read()
imgFile.close()

它输出一张图像,只是一张看似随机数据的图像。

最佳答案

你可能必须open()你的图像文件在 binary mode :

<罢工>
imgfile = open("%s.png" % imageid, "rb")
print imgfile.read()

<罢工>

在 Windows 上,您需要 explicitly制造stdout二进制:

import sys
if sys.platform == "win32":
    import os, msvcrt
    msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)

您可能还想在 header 之间使用 CR+LF 对(参见 RFC 2616 第 6 节):

imgFile = open(fileName, "rb")
sys.stdout.write("Content-type: image/jpeg\r\n")
sys.stdout.write("\r\n")
sys.stdout.write(imgFile.read())
imgFile.close()

关于python - 使用 Python 通过 http 输出图像时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4176693/

相关文章:

python - 如何使用存储在python字符串变量中的证书打开ssl套接字

重启后 Raspberry Pi 上的 Python 虚拟环境错误

python - 如何使用 python discord api 中的 add_roles 方法

python - 如何在 SQLAlchemy 中表示自定义 PostgreSQL 域?

Python 3.3 : printing special symbols like ♥ and ❦ when running through command line

python - 为什么pytest-django找不到manage.py?

python - 使用 python re.compile 和 beautiful soup 来匹配字符串

python - 如何在Python热图中添加矩形补丁?

python - 如何在 Pytorch 中实现上限 JSD 损失?

python - pandas 通过多个动态列来旋转 DataFrame