python怎么输出图片,使用python将图像输出到html

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

print "

"

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

...

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:

Also, if I try:

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

解决方案

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 = ''.format(data_uri)

print(img_tag)

Alternatively for Python <2.6:

data_uri = open('11.png', 'rb').read().encode('base64').replace('\n', '')

img_tag = '' % data_uri

print(img_tag)

For python >3 replace first line by

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值