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 Imageimg = 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...
圖片處理過程
圖片轉換成網頁的過程,可以分成五個步驟。首先要選擇一個合適的HTML模板,控制好字體的大小和字符間的間距。
然后通過 Python 的 網絡訪問模塊,根據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>'''↑ 大括號代表一個占位符,最后會被替換成實際內容,雙大括號中的內容則不會被替換。
獲取圖片
from urllib import requesturl = 'https://pic.cnblogs.com/avatar/875028/20160405220401.png'binary = request.urlopen(url).read()
↑ 通過 URL 得到 byte 數組形式的圖片。
處理圖片
from PIL import Imagefrom io import BytesIOimg = 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'
新聞熱點
疑難解答