Python批量添加水印的優(yōu)雅實(shí)現(xiàn)與進(jìn)階
1. 簡介
在日常圖像處理中,為圖片添加水印是一項(xiàng)常見任務(wù)。有多種方法和工具可供選擇,而今天我們將專注于使用Python語言結(jié)合PIL庫批量添加水印。
需要注意的是,所選用的圖片格式不應(yīng)為JPG或JPEG,因?yàn)檫@兩種格式的圖片不支持透明度設(shè)置。
2. PIL庫概述
先前的文章已經(jīng)詳細(xì)介紹過PIL庫,這里不再贅述。
- PIL是Python的圖像處理庫,支持多種文件格式。
- PIL提供強(qiáng)大的圖像和圖形處理功能,包括縮放、裁剪、疊加以及添加線條、文字等操作。
- 安裝PIL庫可使用以下命令:
pip install Pillow

3. PIL庫中涉及的類
| 模塊或類 | 說明 |
|---|---|
| image模塊 | 用于圖像處理 |
| ImageDraw | 2D圖像對(duì)象 |
| ImageFont | 字體存儲(chǔ) |
| ImageEnhance | 圖像增強(qiáng) |
4. 實(shí)現(xiàn)原理
本文的主要目標(biāo)是批量為某個(gè)文件夾下的圖片添加水印,實(shí)現(xiàn)原理如下:
- 設(shè)置水印內(nèi)容;
- 使用Image對(duì)象的open()方法打開原始圖片;
- 使用Image對(duì)象的new()方法創(chuàng)建存儲(chǔ)水印圖片的對(duì)象;
- 使用ImageDraw.Draw對(duì)象的text()方法繪制水印文字;
- 使用ImageEnhance中Brightness的enhance()方法設(shè)置水印透明度。
5. 實(shí)現(xiàn)過程
5.1 原始圖片
設(shè)定原始圖片的存儲(chǔ)目錄,例如:
F:\python_study\image\image01
5.2 導(dǎo)入相關(guān)模塊
導(dǎo)入所需的PIL模塊或類:
from PIL imort Image, ImageDraw, ImageFont, ImageEnhance import os
5.3 初始化數(shù)據(jù)
通過用戶手動(dòng)輸入相關(guān)信息,如圖片存儲(chǔ)路徑、水印文字、水印位置、水印透明度等:
class WatermarkText():
def __init__(self):
super(WatermarkText, self).__init__()
self.image_path = input('圖片路徑:')
self.watermark_text = input('水印文字:')
self.position_flag = int(input('水印位置(1:左上角,2:左下角,3:右上角,4:右下角,5:居中):'))
self.opacity = float(input('水印透明度(0—1之間的1位小數(shù)):'))
5.4 水印字體設(shè)置
選擇系統(tǒng)字體庫中的字體:
self.font = ImageFont.truetype("cambriab.ttf", size=35)
5.5 打開原始圖片并創(chuàng)建存儲(chǔ)對(duì)象
打開原始圖片并轉(zhuǎn)換為RGBA:
image = Image.open(img).convert('RGBA')
創(chuàng)建繪制對(duì)象:
new_img = Image.new('RGBA', image.size, (255, 255, 255, 0))
image_draw = ImageDraw.Draw(new_img)
5.6 計(jì)算圖片和水印的大小
計(jì)算圖片大?。?/p>
w, h = image.size
計(jì)算文字大?。?/p>
w1 = self.font.getsize(self.watermark_text)[0] h1 = self.font.getsize(self.watermark_text)[1]
5.7 選擇性設(shè)置水印文字
通過if語句實(shí)現(xiàn):
if self.position_flag == 1: # 左上角
location = (0, 0)
elif self.position_flag == 2: # 左下角
location = (0, h - h1)
elif self.position_flag == 3: # 右上角
location = (w - w1, 0)
elif self.position_flag == 4: # 右下角
location = (w - w1, h - h1)
elif self.position_flag == 5: # 居中
location = (h/2, h/2)
5.8 繪制文字并設(shè)置透明度
繪制文字:
image_draw.text(location, self.watermark_text, font=self.font, fill="blue")
設(shè)置透明度:
transparent = new_img.split()[3] transparent = ImageEnhance.Brightness(transparent).enhance(self.opacity) new_img.putalpha(transparent) Image.alpha_composite(image, new_img).save(img)
5.9 遍歷獲取圖片文件并調(diào)用繪制方法
watermark_text = WatermarkText()
try:
file_list = os.listdir(watermark_text.image_path)
for i in range(0, len(file_list)):
filepath = os.path.join(watermark_text.image_path, file_list[i])
if os.path.isfile(filepath):
filetype = os.path.splitext(filepath)[1]
if filetype == '.png':
watermark_text.add_text_watermark(filepath)
else:
print("圖片格式有誤,請使用png格式圖片")
print('批量添加水印完成')
except:
print('輸入的文件路徑有誤,請檢查~~')
6. 完整源碼
from PIL import
Image, ImageDraw, ImageFont, ImageEnhance
import os
class WatermarkText():
def __init__(self):
super(WatermarkText, self).__init__()
self.image_path = input('圖片路徑:')
self.watermark_text = input('水印文字:')
self.position_flag = int(input('水印位置(1:左上角,2:左下角,3:右上角,4:右下角,5:居中):'))
self.opacity = float(input('水印透明度(0—1之間的1位小數(shù)):'))
# 設(shè)置字體
self.font = ImageFont.truetype("cambriab.ttf", size=35)
# 文字水印
def add_text_watermark(self, img):
global location
image = Image.open(img).convert('RGBA')
new_img = Image.new('RGBA', image.size, (255, 255, 255, 0))
image_draw = ImageDraw.Draw(new_img)
w, h = image.size # 圖片大小
w1 = self.font.getsize(self.watermark_text)[0] # 字體寬度
h1 = self.font.getsize(self.watermark_text)[1] # 字體高度
# 設(shè)置水印文字位置
if self.position_flag == 1: # 左上角
location = (0, 0)
elif self.position_flag == 2: # 左下角
location = (0, h - h1)
elif self.position_flag == 3: # 右上角
location = (w - w1, 0)
elif self.position_flag == 4: # 右下角
location = (w - w1, h - h1)
elif self.position_flag == 5: # 居中
location = (h/2, h/2)
# 繪制文字
image_draw.text(location, self.watermark_text, font=self.font, fill="blue")
# 設(shè)置透明度
transparent = new_img.split()[3]
transparent = ImageEnhance.Brightness(transparent).enhance(self.opacity)
new_img.putalpha(transparent)
Image.alpha_composite(image, new_img).save(img)
if __name__ == "__main__":
watermark_text = WatermarkText()
try:
file_list = os.listdir(watermark_text.image_path)
for i in range(0, len(file_list)):
filepath = os.path.join(watermark_text.image_path, file_list[i])
if os.path.isfile(filepath):
filetype = os.path.splitext(filepath)[1]
if filetype == '.png':
watermark_text.add_text_watermark(filepath)
else:
print("圖片格式有誤,請使用png格式圖片")
print('批量添加水印完成')
except:
print('輸入的文件路徑有誤,請檢查~~')
7. 效果展示
運(yùn)行過程:
D:\Python37\python.exe F:/python_study/python_project/watermark_text.py
圖片路徑:F:\python_study\image\image01
水印文字:
水印位置(1:左上角,2:左下角,3:右上角,4:右下角,5:居中):1
水印透明度(0—1之間的1位小數(shù)):0.5
F:/python_study/python_project/watermark_text.py:32: DeprecationWarning: getsize is deprecated and will be removed in Pillow 10 (2023-07-01). Use getbbox or getlength instead.
w1 = self.font.getsize(self.watermark_text)[0] # 獲取字體寬度
F:/python_study/python_project/watermark_text.py:33: DeprecationWarning: getsize is deprecated and will be removed in Pillow 10 (2023-07-01). Use getbbox or getlength instead.
h1 = self.font.getsize(self.watermark_text)[1] # 獲取字體高度
批量添加水印完成
8. 改進(jìn)與建議
8.1 參數(shù)輸入方式優(yōu)化
在初始化數(shù)據(jù)的部分,我們可以考慮通過命令行參數(shù)或配置文件的方式輸入相關(guān)信息,以提高用戶體驗(yàn)。例如使用argparse庫來解析命令行參數(shù)。
import argparse
class WatermarkText():
def __init__(self):
parser = argparse.ArgumentParser(description='Add watermark to images.')
parser.add_argument('--image_path', type=str, help='Path to the image directory.')
parser.add_argument('--watermark_text', type=str, help='Text for watermark.')
parser.add_argument('--position_flag', type=int, help='Position flag for watermark (1: top-left, 2: bottom-left, 3: top-right, 4: bottom-right, 5: center).')
parser.add_argument('--opacity', type=float, help='Opacity for watermark (0-1 with 1 decimal place).')
args = parser.parse_args()
self.image_path = args.image_path or input('Image path: ')
self.watermark_text = args.watermark_text or input('Watermark text: ')
self.position_flag = args.position_flag or int(input('Watermark position (1: top-left, 2: bottom-left, 3: top-right, 4: bottom-right, 5: center): '))
self.opacity = args.opacity or float(input('Watermark opacity (0-1 with 1 decimal place): '))
8.2 異常處理改進(jìn)
在處理異常的部分,我們可以更具體地捕獲異常類型,并提供更友好的提示信息。
try:
# existing code...
except FileNotFoundError:
print('Error: The specified image directory does not exist.')
except PermissionError:
print('Error: Permission denied to access the specified image directory.')
except Exception as e:
print(f'An unexpected error occurred: {e}')
8.3 代碼結(jié)構(gòu)優(yōu)化
可以考慮將一些功能模塊化,提高代碼的可讀性和維護(hù)性。例如,將文字水印的添加功能獨(dú)立成一個(gè)方法。
class WatermarkText():
# existing code...
def add_text_watermark(self, img):
# existing code...
8.4 日志記錄
考慮在程序中添加日志記錄,記錄關(guān)鍵步驟和出錯(cuò)信息,以便于排查問題。
import logging
logging.basicConfig(level=logging.INFO)
class WatermarkText():
# existing code...
def add_text_watermark(self, img):
try:
# existing code...
logging.info(f'Successfully added watermark to {img}')
except Exception as e:
logging.error(f'Error adding watermark to {img}: {e}')
8.5 擴(kuò)展功能
在程序中可以考慮添加更多功能,比如支持不同的水印顏色、字體大小等選項(xiàng),以使程序更加靈活。
這些改進(jìn)和建議將有助于提高程序的穩(wěn)定性、易用性和可維護(hù)性。
當(dāng)然,我們將繼續(xù)改進(jìn)和完善你的代碼。在這一部分,我們會(huì)考慮一些進(jìn)一步的優(yōu)化和改進(jìn)。
9. 優(yōu)化圖片格式檢查
在處理圖片文件時(shí),可以優(yōu)化檢查圖片格式的方式。使用os.path.splitext得到的文件擴(kuò)展名可能包含大寫字母,為了確保匹配,可以將文件擴(kuò)展名轉(zhuǎn)換為小寫。
if filetype.lower() == '.png':
watermark_text.add_text_watermark(filepath)
else:
print("Error: Image format is not supported. Please use PNG format.")
10. 增加用戶交互性
可以考慮在程序中增加更多用戶交互性,比如在成功添加水印后詢問用戶是否繼續(xù)添加水印。
while True:
try:
# existing code...
print('Watermark added successfully.')
another = input('Do you want to add watermark to another image? (yes/no): ').lower()
if another != 'yes':
break
except Exception as e:
logging.error(f'Error: {e}')
這樣,用戶可以選擇是否繼續(xù)添加水印,提高程序的交互性。
11. 多線程處理
如果你需要處理大量圖片,可以考慮使用多線程來加速處理過程。這可以通過concurrent.futures模塊實(shí)現(xiàn)。
from concurrent.futures import ThreadPoolExecutor
# existing code...
if __name__ == "__main__":
watermark_text = WatermarkText()
try:
file_list = os.listdir(watermark_text.image_path)
with ThreadPoolExecutor() as executor:
executor.map(watermark_text.add_text_watermark, [os.path.join(watermark_text.image_path, file) for file in file_list])
print('Batch watermarking completed.')
except Exception as e:
logging.error(f'Error: {e}')
這將允許同時(shí)處理多個(gè)圖片,提高處理速度。
12. 其他優(yōu)化建議
考慮支持更多圖片格式,而不僅限于PNG。你可以使用Pillow庫中的Image.register_open()方法注冊其他格式的圖片打開器。
如果水印文字較長,可以考慮自動(dòng)調(diào)整文字大小,以適應(yīng)圖片。
以上就是Python批量添加水印的優(yōu)雅實(shí)現(xiàn)與進(jìn)階的詳細(xì)內(nèi)容,更多關(guān)于Python添加水印的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
python中scikit-learn機(jī)器代碼實(shí)例
這篇文章給大家分享了關(guān)于python中scikit-learn機(jī)器的代碼實(shí)例內(nèi)容,有興趣的朋友跟著小編測試下。2018-08-08
使用Python實(shí)現(xiàn)自動(dòng)化獲取文件的全面指南
在現(xiàn)代數(shù)據(jù)處理和分析中,文件獲取是不可或缺的第一步,使用 Python 進(jìn)行文件獲取自動(dòng)化,能夠顯著提升效率并降低錯(cuò)誤率,下面我們就來看看具體實(shí)現(xiàn)方法吧2025-07-07
Python私有屬性私有方法應(yīng)用實(shí)例解析
這篇文章主要介紹了Python私有屬性私有方法應(yīng)用場景解析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-09-09
Python數(shù)據(jù)分析之雙色球統(tǒng)計(jì)單個(gè)紅和藍(lán)球哪個(gè)比例高的方法
這篇文章主要介紹了Python數(shù)據(jù)分析之雙色球統(tǒng)計(jì)單個(gè)紅和藍(lán)球哪個(gè)比例高的方法,涉及Python數(shù)值運(yùn)算及圖形繪制相關(guān)操作技巧,需要的朋友可以參考下2018-02-02
Python?np.where()的詳解以及代碼應(yīng)用
numpy里有一個(gè)非常神奇的函數(shù)叫做np.where()函數(shù),下面這篇文章主要給大家介紹了關(guān)于Python?np.where()的詳解以及代碼應(yīng)用的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-08-08
PyCharm安裝配置Qt Designer+PyUIC圖文教程
這篇文章主要介紹了PyCharm安裝配置Qt Designer+PyUIC圖文教程,本文通過圖文并茂的形式給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-05-05

