You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

将Python 2图片网页传输CGI脚本迁移至Python 3遇问题求修正

Python3 CGI脚本无法显示图片的修正方案

问题背景

原Python2 CGI脚本可通过网页<img>标签显示图片缩略图,迁移到Python3后脚本无报错,但图片无法正常显示。

原网页代码:

<img src="./sendthumb.cgi" />

原Python2脚本sendthumb.cgi:

#! /usr/bin/python

from PIL import Image
from StringIO import StringIO
import sys

pic = "testpic.jpg"

im = Image.open(pic)
im.thumbnail((256, 256))
buf = StringIO()
im.save(buf, "JPEG")

sys.stdout.write('Status: 200 OK\r\n')
sys.stdout.write('Content-type: image/jpeg\r\n')
sys.stdout.write('\r\n')
sys.stdout.write(buf.getvalue())

迁移后的Python3脚本:

#! /usr/bin/python3

from PIL import Image
from io import BytesIO
import sys

pic = "testpic.jpg"

im = Image.open(pic)
im.thumbnail((256, 256))
buf = BytesIO()
im.save(buf, "JPEG")

sys.stdout.write('Status: 200 OK\r\n')
sys.stdout.write('Content-type: image/jpeg\r\n')
sys.stdout.write('\r\n')
sys.stdout.buffer.write(buf.getvalue())

修正方法

问题根源是混合使用文本模式的sys.stdout.write()和二进制模式的sys.stdout.buffer.write():Python3中sys.stdout默认是文本流,写字符串时会涉及编码转换,导致HTTP头的字节输出不准确,浏览器无法正确解析头信息和后续的图片二进制数据。

提供两种可行修正方案:

方案1:统一用二进制流输出所有内容

将HTTP头转为字节格式,全部通过sys.stdout.buffer.write()输出:

#! /usr/bin/python3

from PIL import Image
from io import BytesIO
import sys

pic = "testpic.jpg"

im = Image.open(pic)
im.thumbnail((256, 256))
buf = BytesIO()
im.save(buf, "JPEG")

# 所有内容以字节形式输出
sys.stdout.buffer.write(b'Status: 200 OK\r\n')
sys.stdout.buffer.write(b'Content-type: image/jpeg\r\n')
sys.stdout.buffer.write(b'\r\n')
sys.stdout.buffer.write(buf.getvalue())

方案2:先刷新文本流再输出二进制数据

若要保留文本模式写头,需先强制刷新文本流,确保头信息完全发送后再输出图片数据:

#! /usr/bin/python3

from PIL import Image
from io import BytesIO
import sys

pic = "testpic.jpg"

im = Image.open(pic)
im.thumbnail((256, 256))
buf = BytesIO()
im.save(buf, "JPEG")

sys.stdout.write('Status: 200 OK\r\n')
sys.stdout.write('Content-type: image/jpeg\r\n')
sys.stdout.write('\r\n')
# 强制刷新文本流,确保头信息全部输出
sys.stdout.flush()
sys.stdout.buffer.write(buf.getvalue())

额外检查项:

  • 确保sendthumb.cgi有可执行权限,执行命令:chmod +x sendthumb.cgi
  • 确认testpic.jpg路径正确,脚本具备该文件的读取权限
  • 服务器CGI配置支持Python3脚本执行

内容的提问来源于stack exchange,提问作者Andy31

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 01:00:09