stone2083

          將圖片轉成HTML格式--原理&代碼

          之前的文章,因為貼了效果圖,導致無法編輯。
          @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

          主站蜘蛛池模板: 海城市| 海林市| 阿克苏市| 项城市| 黎川县| 北安市| 当涂县| 龙海市| 翼城县| 上蔡县| 射洪县| 拉萨市| 武川县| 泰州市| 古蔺县| 勐海县| 庄浪县| 麦盖提县| 迭部县| 中卫市| 高阳县| 日喀则市| 布尔津县| 开化县| 铜山县| 榆树市| 曲周县| 山丹县| 承德市| 清苑县| 泗水县| 右玉县| 江津市| 苍南县| 崇义县| 湟中县| 万源市| 凤城市| 盈江县| 萨嘎县| 永济市|