2016-11-06 6 views
0

htmlにpng画像を印刷するにはどうすればいいですか?Python cgi 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() 
+0

あなたはヘッダとデータの間に空行を必要とする - ので、あなたは2を必要とする '\ N '。また、データサイズ/長さのヘッダーが必要な場合があります。 – furas

+0

@furas何も変わっていません。 –

+0

btw:あなたはHTMLではなくHTTP本体に印刷します。 – furas

答えて

0

EDIT:Simple CGI Server with CGI scripts in different languages拡張ソースコード は、私はこれを持っています。


CGIサーバは、余分なコードなしで画像を提供することができます(すべてのコードが末尾にある)

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

と私は./server.py(またはpython3 server.py)を実行します。


私は構造を有しています。あなたは、動的に作成した画像が必要な場合は、スクリプトすなわちでフォルダcgi-binを作成

< img src="/image.png" > 

index.htmlで。すなわち)HTMLで

http://localhost:8000/image.png 

またはputタグを試してみて、

http://localhost:8000/index.html 

を実行することができます。 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> 

画像。PNG

enter image description here