Python語言實現(xiàn)將圖片轉化為html頁面
PIL 圖像處理庫
PIL(Python Imaging Library) 是 Python 平臺的圖像處理標準庫。不過 PIL 暫不支持 Python3,可以用 Pillow 代替,API是相同的。
安裝 PIL 庫
如果你安裝了 pip 的話可以直接輸入 pip install PIL 命令安裝 Pillow。
或者在 PyCharm 中打開 [File] >> [settings] >> [project github] >> [project interpreter] 添加標準庫:

↑ 搜索 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') # 圖片轉換
img = img.rotate(180) # 圖片旋轉
img.save('output.jpg') # 保存圖片
↑ PIL 常用模塊:Image, ImageFilter, ImageDraw, ImageFont, ImageEnhance, ImageFilter...
圖片處理過程
圖片轉換成網(wǎng)頁的過程,可以分成五個步驟。首先要選擇一個合適的HTML模板,控制好字體的大小和字符間的間距。
然后通過 Python 的 網(wǎng)絡訪問模塊,根據(jù)URL獲取圖片。接著使用 PIL 模塊載入二進制圖片,將圖片壓縮到合適的尺寸。
遍歷圖片的每一個像素,得到該像素的顏色值,應用到HTML的標簽上。最后把字符串信息輸出到文件中,生成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 轉換為 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>標簽包裹文字,并根據(jù)相應像素的RGB值,設置<font>標簽的color屬性。
導出網(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
導入 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)
↑ 程序會在當前目錄生成 index.html 文件,需要用瀏覽器打開后才可以看到效果。
轉換效果
| 原始圖片 | 輸出HTML |
![]() |
![]() |
總結
以上就是本文關于Python實現(xiàn)將圖片轉化為html頁面的全部內(nèi)容,希望對大家有所幫助。感興趣的朋友可以繼續(xù)參閱本站其他相關專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!
相關文章
python中的多線程鎖lock=threading.Lock()使用方式
這篇文章主要介紹了python中的多線程鎖lock=threading.Lock()使用方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-06-06
三分鐘教會你用Python+OpenCV批量裁剪xml格式標注的圖片
最近學習網(wǎng)絡在線課程的過程中,為了方便課后復習,使用手機截取了大量的圖片,下面這篇文章主要給大家介紹了如何通過三分鐘教會你用Python+OpenCV批量裁剪xml格式標注圖片的相關資料,需要的朋友可以參考下2022-01-01
Python 通過監(jiān)聽端口實現(xiàn)唯一腳本運行方式
這篇文章主要介紹了Python 通過監(jiān)聽端口實現(xiàn)唯一腳本運行方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-05-05
關于flask路由app.route及路由參數(shù)的各種用法解析
我們在開發(fā)過程中,編寫項目時所使用的路由往往是指代了框架/項目中用于完成路由功能的類,這個類一般就是路由類,簡稱路由,這篇文章主要介紹了有關flask路由app.route及路由參數(shù)的各種用法解析,需要的朋友可以參考下2024-03-03
Ubuntu下創(chuàng)建虛擬獨立的Python環(huán)境全過程
virtualenv可以搭建虛擬且獨立的python環(huán)境,可以使每個項目環(huán)境與其他項目獨立開來,保持環(huán)境的干凈,解決包沖突問題。本篇文章講述如何在Linux以及Ubuntu中創(chuàng)建Python虛擬環(huán)境,以及Virtualenvwrapper的安裝使用,需要的朋友可以參考借鑒,下面來一起看看吧。2017-02-02
python 兩個數(shù)據(jù)庫postgresql對比
這篇文章主要介紹了python 兩個數(shù)據(jù)庫postgresql對比,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2019-10-10



