前言
最近在博客中做了一個相冊功能,但是問題是我的圖片都很大,用圖片壓縮工具壓縮了一遍感覺不是很方便,于是就搜了一下python相關(guān)工具,后來發(fā)現(xiàn)知乎上的一篇文章《如何用Python智能批量壓縮圖片》,這里感謝作者提供了思路,短短幾行代碼實現(xiàn)了圖片壓縮需求。
最后添加了圖片水印功能,可以方便配置圖片路徑來實現(xiàn)壓縮和水印添加,本來打算使用 Tkinter 來實現(xiàn)一個圖片界面方便操作,后來想想還是把精力放在核心邏輯上面吧,其實使用圖形界面不見的就很方便,這樣修改配置其實更方便些,如果你想實現(xiàn)成圖形界面可參考我的另一篇博文《Python兩個案例練習(xí)》。
知識點
內(nèi)置模塊和第三方模塊
在 python 中,一個 .py 文件就可以理解為一個模塊,模塊之間可以互相引用。
模塊分為三種:自己寫的、內(nèi)置的、第三方的。
內(nèi)置模塊一般存放在安裝目錄的lib目錄下,第三方庫一般存放在安裝目錄的lib\site-packages目錄下。第三方庫使用前需要提前安裝,例如 Python 操作圖像的模塊 PIL 需要提前安裝。
兩種導(dǎo)入方式,例如下面導(dǎo)入module1 并調(diào)用模塊方法 say():
#第一種導(dǎo)入方式
import module1
module1.say()
#第二種導(dǎo)入方式
from module1 import *
say()
from …import 提供了一個簡單的方法來導(dǎo)入一個模塊中的所有項目。然而這種聲明不該被過多地使用。
PIL模塊
PIL:Python Imaging Library,已經(jīng)是 Python 平臺事實上的圖像處理標(biāo)準(zhǔn)庫了。PIL 功能非常強大,但 API 卻非常簡單易用。
安裝:
在 Debian/Ubuntu Linux 下直接通過apt安裝:$ sudo apt-get install python-imaging
Windows 平臺就去 PIL官方網(wǎng)站 下載 exe 安裝包。
在本文中我安裝的是 Pillow,Pillow 是一個對 PIL 友好的分支,作者是 Alex Clark 和貢獻(xiàn)者。而 PIL 是一個 Python 圖像處理庫,作者是 Fredrik Lundh 和貢獻(xiàn)者。
有關(guān) Pillow 的中文文檔請參考這里
glob模塊
glob 是 python 的內(nèi)置模塊,是一個文件操作相關(guān)模塊,用它可以查找符合自己目的文件。
截止目前官方最新 python 版本是 3.7.3,該版本的標(biāo)準(zhǔn)庫文檔鏈接——點這里查看
壓縮實現(xiàn)
下面是用 PIL 實現(xiàn)的圖片壓縮函數(shù),可直接粘貼修改目錄使用(記得安裝Pillow)。
#coding=utf-8
#!/usr/bin/python
from glob import glob
#pip install Pillow
from PIL import Image
import os
import math
SORUCE_DIR = 'D:\\blog\\gitlab\\source\\images\\photo'
TARGET_DIR= 'D:\\blog\\gitlab\\source\\images\\photo\\thumb'
THRESHOLD = 100000 #100kb
NEW_W_H = 800
def resize_images(source_dir, target_dir, threshold, new_w_or_h):
filenames = glob('{}/*'.format(source_dir))
if not os.path.exists(target_dir):
os.makedirs(target_dir)
for filename in filenames:
filesize = os.path.getsize(filename)
if filesize >= threshold:
print(filename)
with Image.open(filename) as im:
width, height = im.size
if width >= height:
new_width = new_w_or_h
new_height = int(new_width * height * 1.0 / width)
else:
new_height = new_w_or_h
new_width = int(new_height * width * 1.0 / height)
resized_im = im.resize((new_width, new_height))
output_filename = filename.replace(source_dir, target_dir)
resized_im.save(output_filename)
resize_images(SORUCE_DIR, TARGET_DIR, THRESHOLD, NEW_W_H)
添加水印
#預(yù)定義一個字體
FONT_FAMILY = 'C:\\Windows\\Fonts\\consola.ttf'
def add_text_to_image(image, text, font_size, font_family=FONT_FAMILY):
width, height = image.size
#相當(dāng)于將圖片轉(zhuǎn)換為可以繪制的畫布
img_draw = ImageDraw.Draw(image)
#創(chuàng)建字體畫筆
Font = ImageFont.truetype(font_family, font_size)
#獲取文字尺寸
textW,textH = Font.getsize(text)
#將文字寫在屏幕右下角,文字白色透明度100/255
pointX = width - textW - textH / 2
pointY = height - textH - textH / 2
img_draw.text([pointX, pointY], text, fill=(255, 255, 255, 100), font = Font)
add_text_to_image(resized_im, "dp2px.com", 30)
完整代碼
#coding=utf-8
#!/usr/bin/python
from glob import glob
#pip install Pillow
from PIL import Image, ImageDraw, ImageFont
import os
import math
#原始圖片目錄
SORUCE_DIR = 'D:\\blog\\gitlab\\source\\images\\photo'
#處理后圖片目錄
TARGET_DIR= 'D:\\blog\\gitlab\\source\\images\\photo\\thumb'
#圖片篩選條件
THRESHOLD = 100000 #100kb
#圖片最大寬/高
NEW_W_H = 800
#是否開啟水印 0不開啟 1開啟
WAHTER_MARK = 0
FONT_FAMILY = 'C:\\Windows\\Fonts\\constan.ttf'
def add_text_to_image(image, text, font_size, font_family=FONT_FAMILY):
width, height = image.size
#相當(dāng)于將圖片轉(zhuǎn)換為可以繪制的畫布
img_draw = ImageDraw.Draw(image)
#創(chuàng)建字體畫筆
Font = ImageFont.truetype(font_family, font_size)
#獲取文字尺寸
textW,textH = Font.getsize(text)
#將文字寫在空白圖像正中間
pointX = width - textW - textH / 2
pointY = height - textH - textH / 2
img_draw.text([pointX, pointY], text, fill=(255, 255, 255, 100), font = Font)
def resize_images(source_dir, target_dir, threshold, new_w_or_h):
#讀取目錄下所有文件
filenames = glob('{}/*'.format(source_dir))
#判斷輸出目錄
if not os.path.exists(target_dir):
os.makedirs(target_dir)
#遍歷處理
for filename in filenames:
filesize = os.path.getsize(filename)
#比較篩選
if filesize >= threshold:
with Image.open(filename) as im:
width, height = im.size
#判斷圖片方向(橫/豎)
if width >= height:
new_width = new_w_or_h
new_height = int(new_width * height * 1.0 / width)
else:
new_height = new_w_or_h
new_width = int(new_height * width * 1.0 / height)
resized_im = im.resize((new_width, new_height))
#判斷是否添加水印
if WAHTER_MARK != 0:
add_text_to_image(resized_im, "dp2px.com", int(new_w_or_h / 30))
#保存到輸出目錄
output_filename = filename.replace(source_dir, target_dir)
resized_im.save(output_filename)
print('圖片處理完成!')
#調(diào)用處理方法處理圖片
resize_images(SORUCE_DIR, TARGET_DIR, THRESHOLD, NEW_W_H)
啰嗦一句
最后給他家推薦一個編輯器來編輯和運行python程序,準(zhǔn)確的說應(yīng)該是一個插件。
編輯器:Visual Studio Code
插件:Code Runner
這個插件目前幾乎支持所有語言的編譯和運行,非常好用方便,安裝好后操作欄會多出一個運行的小三角按鈕,點擊運行即可。
作者:水寒
出處:https://dp2px.com/2019/03/26/python-compress/#more
51reboot 在8.23日(周五)《基于云服務(wù)的 DevOps工作流》 分享
時間:8.23日21:00-22:00
分享內(nèi)容如下:
1、 背景
2 、工作流引擎
3、 用例
4 、演示
分享人:
架構(gòu)師萊米,目前就職于某外企云服務(wù)商。
10多年的軟件開發(fā)和團(tuán)隊管理經(jīng)驗,豐富的互聯(lián)網(wǎng)應(yīng)用和企業(yè)應(yīng)用架構(gòu)項目經(jīng)歷。