Python cgi打印图像到html

时间:2016-11-06 15:03:39

标签: python html image cgi

如何将png图像打印到html?

我有:

print("Content-Type: image/png\n")
print(open('image.png', 'rb').read())

它打印出来:

Content-Type: image/png
b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x0 ...

That回答没有帮助我。 我有这个:

Content-Type: image/png �PNG  IHDR�X��%sBIT|d�  pHYsaa�?�i IDAT...

HTTP服务器:

from http.server import HTTPServer, CGIHTTPRequestHandler
server_address = ("", 8000)
httpd = HTTPServer(server_address, CGIHTTPRequestHandler)
httpd.serve_forever()

1 个答案:

答案 0 :(得分:0)

编辑 Simple CGI Server with CGI scripts in different languages中的扩展源代码。

我有结构:(所有代码都在最后)

project
├── cgi-bin
│   └── image.py
├── image.png
├── index.html
└── server.py

我运行./server.py(或python3 server.py

CGI服务器可以在没有额外代码的情况下提供图像。你可以尝试

http://localhost:8000/image.png

或者将标记放入HTML(即index.html

< img src="/image.png" > 

并运行

http://localhost:8000/index.html

如果您需要动态创建的图像,则使用脚本创建文件夹cgi-bin,即。 image.py
(在Linux上,您必须设置执行属性chmod +x image.py

然后你可以直接运行这个脚本

http://localhost:8000/cgi-bin/image.py

或HTML

< img src="/cgi-bin/image.py" >

<强> server.py

#!/usr/bin/env python3

from http.server import HTTPServer, CGIHTTPRequestHandler

server_address = ("", 8000)

httpd = HTTPServer(server_address, CGIHTTPRequestHandler)
httpd.serve_forever()

<强>的cgi-bin / image.py

#!/usr/bin/env python3

import sys
import os

src =  "image.png"

sys.stdout.write("Content-Type: image/png\n")
sys.stdout.write("Content-Length: " + str(os.stat(src).st_size) + "\n")
sys.stdout.write("\n")
sys.stdout.flush()
sys.stdout.buffer.write(open(src, "rb").read())

<强>的index.html

<!DOCTYPE html>

<html>

<head>
    <meta charset="utf-8"/>
    <title>Index</title>
</head>

<body>
    <h1>image.png</h1>
    <img src="/image.png">

    <h1>cgi-bin/image.py</h1>
    <img src="/cgi-bin/image.py">    
</body>

</html>

<强> image.png

enter image description here