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 模塊載入二進制圖片,將圖片壓縮到合適的尺寸。
遍歷圖片的每一個像素,得到該像素的顏色值,應(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)文章
關(guān)于Python八大排序?qū)崿F(xiàn)方法(冒泡排序、快速排序等)
這篇文章主要介紹了關(guān)于Python八大排序?qū)崿F(xiàn)方法,主要有基數(shù)排序、歸并排序、堆排序、簡單選擇排序、直接插入排序、希爾排序、快速排序、冒泡排序等,需要的朋友可以參考下2023-03-03
Python實現(xiàn)發(fā)送帶有pdf附件的電子郵件
使用Python發(fā)郵件,是個簡單的話題,可是如何可以優(yōu)雅的輕松的群發(fā)郵件,并附加PDF附件,是很多小伙伴的日常工作。本文就來和大家分享一下實現(xiàn)方法,需要的可以參考一下2023-02-02
Python實現(xiàn)雙軸組合圖表柱狀圖和折線圖的具體流程
這篇文章主要介紹了Python雙軸組合圖表柱狀圖+折線圖,Python繪制雙軸組合的關(guān)鍵在plt庫的twinx()函數(shù),具體實例代碼跟隨小編一起看看吧2021-08-08
python環(huán)境下OPenCV處理視頻流局部區(qū)域像素值
這篇文章主要為大家介紹了python環(huán)境下OPenCV處理視頻流局部區(qū)域像素值的實現(xiàn)示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步2021-11-11
解決安裝tensorflow遇到無法卸載numpy 1.8.0rc1的問題
今天小編就為大家分享一篇解決安裝tensorflow遇到無法卸載numpy 1.8.0rc1的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-06-06
django框架基于queryset和雙下劃線的跨表查詢操作詳解
這篇文章主要介紹了django框架基于queryset和雙下劃線的跨表查詢操作,結(jié)合實例形式詳細(xì)分析了Django框架queryset和雙下劃線的跨表查詢相關(guān)實現(xiàn)技巧與操作注意事項,需要的朋友可以參考下2019-12-12



