Александра Александра - 28 days ago 6
HTML Question

Python cgi print image to html

How to print a png image to html?

I have:

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


And it prints that:

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


That answer didn't help me.
I have this:

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


HTTP Server:

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

Answer

I have structure: (all code is at the end)

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

and I run ./server.py (or python3 server.py)


CGI server can serve images without extra code. You can try

http://localhost:8000/image.png

Or put tag in HTML (ie. in index.html)

< img src="/image.png" > 

and run

http://localhost:8000/index.html

If you need dynamically created image then create folder cgi-bin with script ie. image.py (on Linux you have to set execution attribut chmod +x image.py)

And then you can run this script directly

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

or in 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

Comments