把图片转为 HTML

 2015-01-08    大连 /python/2015/01/08/img2html.html python nil

本文最近更新于 2017 年 10 月 09 日

Python 是一门优雅而健壮的编程语言,它继承了传统编译语言的强大性和通用性,同时也借鉴了简单脚本和解释语言的易用性。
Python 编程简明教程 https://jsntn.com/python

!本文代码存放在 gist。

示例:

anonymous.html

运行以下代码前先安装 Python Image Library 或者 Pillow。

Code1:

#!/usr/bin/python
import sys, optparse, Image

TABLE='<table id="image" border="0" cellpadding="0" cellspacing="0">%s</table>'
TR='<tr>%s</tr>'
TD='<td width="1px;" height="1px;" bgcolor="%s"/>'

def rgb2hex(rgb):
    return '#{:02x}{:02x}{:02x}'.format(rgb[0],rgb[1],rgb[2])

def get_image(name, thumbnail=1):
    if(thumbnail >= 1 or thumbnail <= 0):
        return Image.open(name)
    else:
        img = Image.open(name)
        return img.resize((int(img.size[0] * thumbnail),int(img.size[1] * thumbnail)))

def convert(img):
    trs = []
    for height in xrange(img.size[1]):
        tds = []
        for width in xrange(img.size[0]):
            tds.append(TD % rgb2hex(img.getpixel((width, height))))
        trs.append(TR % (''.join(tds)))
    return TABLE % (''.join(trs),)

parser = optparse.OptionParser('Usage: %prog [options] image')
parser.add_option('-c', '--compress', dest='thumbnail', default='1', metavar='float', help='specify the compress value (0, 1)')
parser.add_option('-o', '--out', dest='out', default='out.html', help='specify the output file')
opts, args = parser.parse_args()

if(len(args) != 1):
    parser.print_help()
    sys.exit(-1)

html = open(opts.out,'w')
html.write(convert(get_image(args[0], float(opts.thumbnail))))
html.close()

via: https://code.google.com/p/stonelab/

Usage:

python img2html.py [options] image

Options:
-h, –help #show this help message and exit
-c float, –compress=float #specify the compress value (0, 1)
-o OUT, –out=OUT #specify the output file

例如:
python img2html.py -c 0.5 -o output.html input.jpg #将 input.jpg 图片转为以 output.html 命名的 HTML 代码文件,尺寸为原图的 50%。

Code2:

"""
Copyright 2011 HubSpot, Inc.
  Licensed under the Apache License, Version 2.0 (the 
"License"); you may not use this file except in compliance 
with the License.
  You may obtain a copy of the License at
      https://www.apache.org/licenses/LICENSE-2.0
  Unless required by applicable law or agreed to in writing, 
software distributed under the License is distributed on an 
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 
either express or implied.  See the License for the specific 
language governing permissions and limitations under the 
License.
"""

import sys
from PIL import Image

# Check args
if not len(sys.argv) > 1:
    sys.exit("Please specify an input file!")

# Get RGB image data
image = Image.open(sys.argv[1])
image = image.convert('RGB')
pixels = image.load()
width, height = image.size

# Start table
print '<html><body>'
print '<table width="%spx" height="%spx" cellpadding="0" cellspacing="0">' % (width, height)

# Loop through rows
run_length = 1
for row in xrange(height):
    print '<tr>'
    
    # Loop through columns
    for col in xrange(width):

        # If this is not first row (to make sure we get all columns), the last column, and this is part of a run, increase colspan
        if row != 0 and col < width - 1 and pixels[col, row] == pixels[col + 1, row]:
            run_length = run_length + 1
        
        # If there is no run, or this is the end of a run, output this pixel (with no newline)
        else:
            color = '#%x%x%x' % pixels[col, row]
            colspan = 'colspan="%s"' % run_length if run_length > 1 else ''
            print '<td bgcolor="%s" width="%spx" height="1px" %s></td>' % (color, run_length, colspan),
            run_length = 1

    print '</tr>'

# Finish up
print '</table>'
print '</body></html>'

via: https://github.com/HubSpot/img2html

This script reads from the specified image file and outputs to stdout.

Usage:

python img2html.py image.png

Code3:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

## @package img2html
#  Usage        : img2html.py file1|dir1 [file2|dir2 ...]
#  Description  : generate html uses box-shadow to show picture
#                 or a html to show your image sequence in a folder as css animation
#  Dependencies : Python Image Library or Pillow, Python 3
#  Note         : Take care of the Super-High-Energy output ( >﹏<。)
#  Date         : 2014-12-19
#  Author       : frantic1048


import sys
import os
from PIL import Image
from string import Template

class UnknownColorMode(Exception): pass

## @var tHTML template for constructing entire html document
tHTML = Template('''
<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>~ ${name} ~</title>
</head>
<body>
  <style type="text/css">${css}</style>
  <div id="image_kun"></div>
</body>
</html>''')

## @var tCSSStatic template for constructing static image's css code
tCSSStatic = Template('''
@charset "utf-8";
body{
  display:flex;
  justify-content:center;
  align-items:center;
}
#image_kun{
  height: ${height}px;
  width: ${width}px;
  position:relative;
}
#image_kun::after{
  position:absolute;
  height:1px;
  width:1px;
  background:${firstPixel};
  margin:0;
  padding:0;
  content:"\\200B";/*ZWS*/
  box-shadow:
  ${boxshadow};
}
''')

## @var tCSSAnimation template for constructing image sequence's css animation code
tCSSAnimation = Template('''
@charset "utf-8";
body{
  display:flex;
  justify-content:center;
  align-items:center;
}
#image_kun{
  height: ${height}px;
  width: ${width}px;
  position:relative;
}
#image_kun::after{
  position:absolute;
  height:1px;
  width:1px;
  background:transparent;
  margin:0;
  padding:0;
  content:"\\200B";/*ZWS*/
  animation:ayaya ${animationLength} step-end infinite alternate;
}
${animationKeyFrames}
  ''')

## @var tCSSKeyframes template entire CSS keyframes rule
tCSSKeyframes = Template('@keyframes ayaya {${keyframes}}')

## @var tCSSKeyframe template for a single CSS keyframe
tCSSKeyframe = Template('${percentage}% {${keyframeRule}}\n')

## @var tCSSKeyframeRule template for a single CSS keyframe inner rule
tCSSKeyframeRule = Template('background:${firstPixel};box-shadow:${boxshadow};')

## ensure no trailiing slash in directory name
def toRegularDirName(dirName):
    if (os.path.split(dirName)[-1] == ''):
      return os.path.split(dirName)[0]
    else:
      return dirName

## write str to a file,named as <exportFileName>.html
def toFile (str,exportFileName):
  with open (exportFileName,'w') as html:
    html.write(str)

## construct HEX Color value for a pixel
#  @param pixel a RGB mode pixel object to be converted
#  @return CSS hex format color value
def toHexColor (pixel):
  return '#{0:02x}{1:02x}{2:02x}'.format(*pixel[:])

## construct RGBA Color value for a pixel
#  @param pixel a RGBA mode pixle object to be comverted
#  @return CSS rgba format color value
def toRGBAColor (pixel):
  return 'rgba({0},{1},{2},{3})'.format(*pixel[:])

def toCSSColor (pixel, mode):
  if (mode == 'RGB'):
    return toHexColor(pixel)
  elif (mode == 'RGBA'):
    return toRGBAColor(pixel)
  else:
    raise UnknownColorMode

## construct single box-shadow param
#  @param color valid CSS color
def toBoxShadowParam (x, y, color):
  return format('%spx %spx 0 %s'%(x, y, color))

## process single image file to html
#  @param fileName input file's name
#  @param export output callback(doc, exportFileName):
#    doc : generated html string
#    exportFileName : output filename
def mipaStatic(fileName,export=''):
  with Image.open(fileName) as im:
    ## what called magic
    boxshadow = ''

    ## file name as sysname
    exportFileName = fileName+'.html'
    title = os.path.split(fileName)[-1]

    ## image size
    width, height = im.size[0], im.size[1]

    #ensure RGB(A) mode
    if (im.mode != 'RGBA' or im.mode != 'RGB'):
      im.convert('RGB')

    firstPixel = toCSSColor(im.getpixel((0,0)), im.mode)
    for y in range(0, height):
      for x in range(0, width):
        color = toCSSColor(im.getpixel((x, y)), im.mode)
        #link magic
        boxshadow += toBoxShadowParam(x, y, color)

        #add a spliter if not the end
        if (not (y == height-1 and x == width-1)):
          #keep a '\n' for text editor ˊ_>ˋ
          boxshadow += ',' + '\n'

    doc = tHTML.substitute(name = title, css = tCSSStatic.substitute(width = width, height = height, boxshadow = boxshadow, firstPixel=firstPixel))
    if (export==''):
      print(doc)
    else:
      export(doc, exportFileName)


## process a image folder
#  files in folder will processed to an animated html
#  process order is filename asend
#  @param dirName input file's name
#  @param export output callback, call with generated html as a string argument
def mipaAnimation(dirName,export=''):
  dirName = toRegularDirName(dirName)
  title = os.path.basename(dirName)
  exportFileName = title + '.html'

  files = os.listdir(dirName)
  files.sort()

  FPS = 24
  mode = ''
  width, height = 0, 0
  frameCount = 0
  keyframeRules = []
  keyframe = ''

  for f in files:
    try:
      with Image.open(os.path.join(dirName, f)) as im:

        if (export!=''):print('processing file --> ' + f)

        frameCount+=1

        #ensure RGB(A) mode
        if (im.mode != 'RGBA' or im.mode != 'RGB'):
          im.convert('RGB');

        #collect animation info
        if (width == 0) : width, height = im.size[0], im.size[1]
        if (mode == '') : mode = im.mode

        firstPixel = toCSSColor(im.getpixel((0,0)), mode)
        boxshadow = ''
        for y in range(0, height):
          for x in range(0, width):
            color = toCSSColor(im.getpixel((x, y)), mode)
            #link magic
            boxshadow += toBoxShadowParam(x, y, color)

            #add a spliter if not the end
            if (not (y == height-1 and x == width-1)):
              #keep a '\n' for text editor ˊ_>ˋ
              boxshadow += ',' + '\n'
        keyframeRules.append(tCSSKeyframeRule.substitute(firstPixel=firstPixel,boxshadow=boxshadow))
    except:
      pass

  percentUnit= 100/frameCount
  for i in range(0,frameCount):
    if (i == frameCount - 1):
      pc = '100'
    elif (i == 0):
      pc = '0'
    else:
      pc = str(percentUnit * i)
    keyframe += tCSSKeyframe.substitute(percentage = pc, keyframeRule = keyframeRules[i])

  if (export!=''):print('generating document...')
  doc = tHTML.substitute(name = title, css = tCSSAnimation.substitute(animationLength = str((1000 / FPS) * frameCount) + 'ms',
                                                                          animationKeyFrames = tCSSKeyframes.substitute(keyframes = keyframe),
                                                                          height = height,
                                                                          width = width))
  #output
  if (export==''):
    print(doc)
  else:
    print('Start exporting...')
    export(doc, exportFileName)
    print('Finished exporting !\nenjoy with your magical ' + exportFileName + ' _(:з」∠)_')


for path in sys.argv[1:]:
  if os.path.isfile(path):
    ##export to stdout
    #mipaStatic(path)

    ##export to autonamed file
    mipaStatic(path,toFile)
  elif os.path.isdir(path):
    #mipaAnimation(path)
    mipaAnimation(path,toFile)

via: https://github.com/frantic1048/img2html

关于作者
Jason,80 后,现从事通信行业。安卓玩家一个人的书房朗读者麦子
 英语入门到放弃
 jsntn
 jasonwtien
 jasonwtien
更多…… /about.html

最近更新: