当通过 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/