欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python語言實現(xiàn)將圖片轉(zhuǎn)化為html頁面

 更新時間:2017年12月06日 16:31:18   作者:woider  
這篇文章主要介紹了Python實現(xiàn)將圖片轉(zhuǎn)化為html頁面,具有一定參考價值,需要的朋友可以了解下。

PIL 圖像處理庫

PIL(Python Imaging Library) 是 Python 平臺的圖像處理標(biāo)準(zhǔn)庫。不過 PIL 暫不支持 Python3,可以用 Pillow 代替,API是相同的。

安裝 PIL 庫

如果你安裝了 pip 的話可以直接輸入 pip install PIL 命令安裝 Pillow。

或者在 PyCharm 中打開 [File] >> [settings] >> [project github] >> [project interpreter] 添加標(biāo)準(zhǔn)庫:

↑ 搜索 Pillow 包,選中 Pillow,點擊 Install Package 安裝

PIL 使用方法

from PIL import Image

img = Image.open('source.jpg') # 打開圖片
width, height = img.size # 圖片尺寸

img.thumbnail((width / 2, height / 2)) # 縮略圖
img = img.crop((0, 0, width / 2, width / 2)) # 圖片裁剪
img = img.convert(mode='L') # 圖片轉(zhuǎn)換
img = img.rotate(180) # 圖片旋轉(zhuǎn)
img.save('output.jpg') # 保存圖片

↑ PIL 常用模塊:Image, ImageFilter, ImageDraw, ImageFont, ImageEnhance, ImageFilter...

圖片處理過程

圖片轉(zhuǎn)換成網(wǎng)頁的過程,可以分成五個步驟。首先要選擇一個合適的HTML模板,控制好字體的大小和字符間的間距。

然后通過 Python 的 網(wǎng)絡(luò)訪問模塊,根據(jù)URL獲取圖片。接著使用 PIL 模塊載入二進(jìn)制圖片,將圖片壓縮到合適的尺寸。

遍歷圖片的每一個像素,得到該像素的顏色值,應(yīng)用到HTML的標(biāo)簽上。最后把字符串信息輸出到文件中,生成HTML文檔。

定制模板

TEMPLATE = '''
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>{title}</title>
  <style>
    body {{
      line-height: 1em;
      letter-spacing: 0;
      font-size: 0.6rem;
      background: black;
      text-align: center;
    }}
  </style>
</head>
<body>
  {body}
</body>
</html>
'''

↑ 大括號代表一個占位符,最后會被替換成實際內(nèi)容,雙大括號中的內(nèi)容則不會被替換。

獲取圖片

from urllib import request
url = 'https://pic.cnblogs.com/avatar/875028/20160405220401.png'
binary = request.urlopen(url).read()

↑ 通過 URL 得到 byte 數(shù)組形式的圖片。

處理圖片

from PIL import Image
from io import BytesIO
img = Image.open(BytesIO(binary))
img.thumbnail((100, 100)) # 圖片壓縮

↑ byte 類型的 圖片需要通過 BytesIO 轉(zhuǎn)換為 string 類型,才能被 PIL 處理。

生成HTML

piexl = img.load() # 獲取像素信息
width, height = img.size # 獲取圖像尺寸
body, word = '', '博客園'
font = '<font color="{color}">{word}</font>'
for y in range(height):
  for x in range(width):
    r, g, b = piexl[x, y] # 獲取像素RGB值
    body += font.format(
      color='#{:02x}{:02x}{:02x}'.format(r, g, b),
      word=word[((y * width + x) % len(word))]
    )
  body += '\n<br />\n'

↑ 使用<font>標(biāo)簽包裹文字,并根據(jù)相應(yīng)像素的RGB值,設(shè)置<font>標(biāo)簽的color屬性。

導(dǎo)出網(wǎng)頁

html = TEMPLATE.format(title=word, body=body)
fo = open('index.html', 'w', encoding='utf8')
fo.write(html)
fo.close()

↑向HTML模板中填充處理完成的數(shù)據(jù),使用文件流將字符串以utf8格式輸出到文檔。

img2html

wo把上面五個步驟封裝了起來,這樣一來就可以很方便的調(diào)用了。

from io import BytesIO
from PIL import Image
from PIL import ImageFilter
from urllib import request

TEMPLATE = '''
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>{title}</title>
  <style>
    body {{
      line-height: 1em;
      letter-spacing: 0;
      font-size: 0.6rem;
      background: black;
      text-align: center;
      min-width: {size}em;
    }}
  </style>
</head>
<body>
  {body}
</body>
</html>
'''
class Converter(object):
  def __init__(self, word='田', size=100):
    self.word, self.size = word, size
    self.font = '<font color="{color}">{word}</font>'

  # 讀取url內(nèi)容
  def __network(self, url):
    return request.urlopen(url).read()

  # 處理圖片信息
  def __handle(self, binary):
    img = Image.open(BytesIO(binary)) # 打開制圖片
    img.thumbnail((self.size, self.size)) # 壓縮圖片
    img.filter(ImageFilter.DETAIL) # 圖片增強
    return img

  # 分析圖片像素
  def __analysis(self, img):
    body = ''
    piexls = img.load()
    width, height = img.size
    for y in range(height):
      for x in range(width):
        r, g, b = piexls[x, y]
        body += self.font.format(
          color='#{:02x}{:02x}{:02x}'.format(r, g, b),
          word=self.word[((y * width + x) % len(self.word))]
        )
      body += '\n<br />\n'
    return body
  # 寫入文件內(nèi)容
  def __writefile(self, file, str):
    fo = open(file, 'w', encoding='utf8')
    try:
      fo.write(str)
    except IOError:
      raise Exception
    finally:
      fo.close()

  # 生成html文檔
  def buildDOC(self, url, output):
    try:
      binary = self.__network(url)
      img = self.__handle(binary)
      html = TEMPLATE.format(
        title=self.word,
        body=self.__analysis(img),
        size=self.size
      ) # 向模板中填充數(shù)據(jù)
      self.__writefile(output, html)
    except Exception as err:
      print('Error:', err)
      return False
    else:
      print('Successful!')
      return True

導(dǎo)入 img2html.Converter,調(diào)用 buildDOC(url, out) 方法

from img2html import Converter
conv = Converter('卷福', 120)
url = 'http://www.sznews.com/ent/images/attachement/jpg/site3/20140215/001e4f9d7bf91469078115.jpg'
out = 'index.html'
conv.buildDOC(url, out)

↑ 程序會在當(dāng)前目錄生成 index.html 文件,需要用瀏覽器打開后才可以看到效果。

轉(zhuǎn)換效果

原始圖片 輸出HTML

總結(jié)

以上就是本文關(guān)于Python實現(xiàn)將圖片轉(zhuǎn)化為html頁面的全部內(nèi)容,希望對大家有所幫助。感興趣的朋友可以繼續(xù)參閱本站其他相關(guān)專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!

相關(guān)文章

最新評論