Python向http请求返回图像

问题描述 投票:0回答:1

我在 iis 中使用 *.py 的处理程序“c:...\python.exe %s %s”设置 python。然后想要提供像“https://.../getpng.py?no=1”这样的url来将图像流返回到html,如下所示

<img src="https://.../getpng.py?no=1">

getpng.py 很简单,如下所示。

with open('C:\\inetpub\\wwwroot\\test\\test1.png', 'rb') as f:
    filecontent = f.read()

print('Content-Type: image/png\r\n\r\n')
print(filecontent )

图片路径正确。文件内容正确。但html页面总是显示损坏的图像。 看起来“打印(文件内容)”失败了。有解决这个问题的提示吗?

我尝试了 sys.stdout.write 但这也不起作用。

还尝试了以下方法均无效 print('内容类型:图像/png ' + 文件内容 ) print('内容类型:图像/png {0}'.format(文件内容))

python image printing
1个回答
0
投票

您可以使用base64在网页上显示图像;

import base64

with open('QR.jpg', 'rb') as image_file:
    base64_bytes = base64.b64encode(image_file.read())
    #print(base64_bytes)

    base64_string = base64_bytes.decode()
    print(base64_string) # For insert into the img tag.

比进入html:

<img src="
      data:image/jpeg;
      data:image/jpeg;base64,/9j/4AAQSkZJRgABAQ....
      " alt="QR.jpg" />
© www.soinside.com 2019 - 2024. All rights reserved.