stone2083

          將圖片轉(zhuǎn)成HTML格式--原理&代碼

          之前的文章,因為貼了效果圖,導(dǎo)致無法編輯。
          @see http://www.aygfsteel.com/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 閱讀(3156) 評論(0)  編輯  收藏 所屬分類: python

          主站蜘蛛池模板: 富裕县| 阳春市| 泰来县| 金阳县| 凌云县| 古田县| 九龙县| 进贤县| 吉首市| 运城市| 泌阳县| 东兴市| 大宁县| 明溪县| 荣昌县| 莫力| 大洼县| 肇源县| 海安县| 新泰市| 鄄城县| 昌邑市| 伊春市| 灌云县| 板桥市| 南丹县| 新干县| 饶河县| 乌鲁木齐县| 开鲁县| 西吉县| 察隅县| 开化县| 汉沽区| 横山县| 乌拉特前旗| 青海省| 弋阳县| 麻城市| 乌兰县| 唐海县|