stone2083

将图片转成HTML格式--原理&代码

之前的文章,因为贴了效果图,导致无法编辑。
@see http://www.blogjava.net/stone2083/archive/2013/12/20/407807.html

原理

使用table,tr/td作为一个像素点,画点。



代码

 2 import sys, optparse, Image
 3 
 4 TABLE='<table id="image" border="0" cellpadding="0" cellspacing="0">%s</table>'
 5 TR='<tr>%s</tr>'
 6 TD='<td width="1px;" height="1px;" bgcolor="%s"/>'
 7 
 8 def rgb2hex(rgb):
 9     return '#{:02x}{:02x}{:02x}'.format(rgb[0],rgb[1],rgb[2])
10 
11 def get_image(name, thumbnail=1):
12     if(thumbnail >= 1 or thumbnail <= 0): 
13         return Image.open(name)
14     else:
15         img = Image.open(name)
16         return img.resize((int(img.size[0] * thumbnail),int(img.size[1] * thumbnail)))
17 
18 def convert(img):
19     trs = []
20     for height in xrange(img.size[1]):
21         tds = []
22         for width in xrange(img.size[0]):
23             tds.append(TD % rgb2hex(img.getpixel((width, height))))
24         trs.append(TR % (''.join(tds)))
25     return TABLE % (''.join(trs),)
26 
27 parser = optparse.OptionParser('Usage: %prog [options] image')
28 parser.add_option('-c''--compress', dest='thumbnail', default='1', metavar='float', help='specify the compress value (0, 1)')
29 parser.add_option('-o''--out', dest='out', default='out.html', help='specify the output file')
30 opts, args = parser.parse_args()
31 
32 if(len(args) != 1): 
33     parser.print_help()
34     sys.exit(-1)
35 
36 html = open(opts.out,'w')
37 html.write(convert(get_image(args[0], float(opts.thumbnail))))
38 html.close()

下载地址 

https://code.google.com/p/stonelab/downloads/detail?name=img2html.py#makechanges

posted on 2013-12-20 14:28 stone2083 阅读(3114) 评论(0)  编辑  收藏 所属分类: python


只有注册用户登录后才能发表评论。


网站导航: