使用python将图像输出到html
我有一个由 python 生成的网页,它应该按预期工作,使用:
print 'Content-type: text/html\n\n'
print "" # blank line, end of headers
print '<link href="default.css" rel="stylesheet" type="text/css" />'
print "<html><head>"
我想将图像添加到该网页,但是当我这样做时:
sys.stdout.write( "Content-type: image/png\n\n" + file("11.png","rb").read() )
print 'Content-type: text/html\n\n'
print "" # blank line, end of headers
print '<link href="default.css" rel="stylesheet" type="text/css" />'
...
我得到的只是图像,那么如果我将图像代码放在我的 html/text 标题下方我得到的只是图像中的文本,即:
<Ï#·öÐδÝZºm]¾|‰k×®]žòåËÛ¶ÃgžyFK–,ÑôéÓU½zuIÒ}÷ݧ&MšH’V¯^?üð¼1±±±zýõ×%IñññÚºu«*W®¬wß}W.—K3gÎÔÌ™ÿw‹Ú””I’¹w¤¥hdÒd½q÷X•Šˆ²m¿þfïÞ½*]º´éÈs;¥¤¤Ø¿ILLÔˆ#rÊ
另外,如果我尝试:
print "<img src='11.png'>"
我在浏览器中得到一个损坏的图像,直接浏览图像会产生 500 内部服务器错误,我的 apache 日志显示:
8)Exec format error: exec of './../../11.png' failed Premature end of script headers: 11.png
I have a webpage generated from python that works as it should, using:
print 'Content-type: text/html\n\n'
print "" # blank line, end of headers
print '<link href="default.css" rel="stylesheet" type="text/css" />'
print "<html><head>"
I want to add images to this webpage, but when I do this:
sys.stdout.write( "Content-type: image/png\n\n" + file("11.png","rb").read() )
print 'Content-type: text/html\n\n'
print "" # blank line, end of headers
print '<link href="default.css" rel="stylesheet" type="text/css" />'
...
All I get is the image, then if I place the image code below my html/text header all I get is the text from the image, ie:
<Ï#·öÐδÝZºm]¾|‰k×®]žòåËÛ¶ÃgžyFK–,ÑôéÓU½zuIÒ}÷ݧ&MšH’V¯^?üð¼1±±±zýõ×%IñññÚºu«*W®¬wß}W.—K3gÎÔÌ™ÿw‹Ú””I’¹w¤¥hdÒd½q÷X•Šˆ²m¿þfïÞ½*]º´éÈs;¥¤¤Ø¿ILLÔˆ#rÊ
Also, if I try:
print "<img src='11.png'>"
I get a broken image in the browser, and browing directly to the image produces a 500 internal server error, with my apache log saying:
8)Exec format error: exec of './../../11.png' failed Premature end of script headers: 11.png
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用此代码直接将图像嵌入到 HTML 中:
Python 3
Python 2.7
或者 Python <2.6:
You can use this code to directly embed the image in your HTML:
Python 3
Python 2.7
Alternatively for Python <2.6:
网页中的图像通常是对服务器的第二次请求。 HTML 页面本身没有图像,仅引用
等图像。然后浏览器向服务器发出第二次请求,并获取图像数据。
将图像和 HTML 一起提供的唯一选择是在
img
标记中使用data:
url。Images in web pages are typically a second request to the server. The HTML page itself has no images in it, simply references to images like
<img src='the_url_to_the_image'>
. Then the browser makes a second request to the server, and gets the image data.The only option you have to serve images and HTML together is to use a
data:
url in theimg
tag.您不能只将图像数据转储到 HTML 中。
您需要提供文件并链接到该文件,或者嵌入以 base64 编码的图像。
You can't just dump image data into HTML.
You need to either have the file served and link to it or embed the image encoded in base64.