使用python将图像输出到html [英] Output images to html using python

查看:901
本文介绍了使用python将图像输出到html的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个从python生成的网页,它的工作原理如下:

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" />'
...

我得到的是图像,如果我将图像代码放在我的html /文本标题下面,我只能看到图像中的文本,即:

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'>"

我在浏览器中看到一张破损的图片,直接向图片浏览会产生500个内部服务器错误,用我的apache日志说:

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 


推荐答案

您可以使用此代码直接将图像嵌入到HTML中:

You can use this code to directly embed the image in your HTML:

data_uri = open('11.png', 'rb').read().encode('base64').replace('\n', '')
img_tag = '<img src="data:image/png;base64,{0}">'.format(data_uri)

print(img_tag)

另外对于Python< 2.6:

Alternatively for Python <2.6:

data_uri = open('11.png', 'rb').read().encode('base64').replace('\n', '')
img_tag = '<img src="data:image/png;base64,%s">' % data_uri

print(img_tag)

对于python > 3将第一行替换为

For python >3 replace first line by

data_uri = base64.b64encode(open('Graph.png', 'rb').read()).decode('utf-8').replace('\n', '')

这篇关于使用python将图像输出到html的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆