PIL
库的应用,结合Python
语言批量对图片添加水印;之前有的文章已经详细介绍过,这里不再赘述了。
PIL
是Python
的一个图像处理库,支持多种文件格式;PIL
提供强大的图像处理和图形处理能力;pip install Pillow
模块或类 | 说明 |
---|---|
image模块 |
用于对图像就行处理 |
ImageDraw |
2D图像对象 |
ImageFont |
存储字体 |
ImageEnhance |
图像增强 |
本文主要目的是批量对某个文件夹下的图片进行添加水印,原理如下:
Image
对象的open()
方法打开原始图片;Image
对象的new()
方法新建存储水印图片对象;Image.Draw.Draw
对象的text()
绘制水印文字;ImageEnhance
中的Brightness
中的enhance()
设置水印透明度。F:\python_study\image\image01
PIL
中的模块或类:from PIL import Image, ImageDraw, ImageFont, ImageEnhance
import os
class TestText():
def __init__(self):
super(TestText, self).__init__()
self.pic_path = input('图片路径:')
self.pic_text = input('水印文字:')
self.p_flag = int(input('水印位置(1:左上角,2:左下角,3:右上角,4:右下角,5:居中):'))
self.a = float(input('水印透明度(0—1之间的1位小数):'))
ImageFont.truetype
源码:def truetype(font=None, size=10, index=0, encoding="", layout_engine=None):
"""
Load a TrueType or OpenType font from a file or file-like object,
and create a font object.
This function loads a font object from the given file or file-like
object, and creates a font object for a font of the given size.
Pillow uses FreeType to open font files. On Windows, be aware that FreeType
will keep the file open as long as the FreeTypeFont object exists. Windows
limits the number of files that can be open in C at once to 512, so if many
fonts are opened simultaneously and that limit is approached, an
``OSError`` may be thrown, reporting that FreeType "cannot open resource".
A workaround would be to copy the file(s) into memory, and open that instead.
This function requires the _imagingft service.
:param font: A filename or file-like object containing a TrueType font.
If the file is not found in this filename, the loader may also
search in other directories, such as the :file:`fonts/`
directory on Windows or :file:`/Library/Fonts/`,
:file:`/System/Library/Fonts/` and :file:`~/Library/Fonts/` on
macOS.
:param size: The requested size, in pixels.
:param index: Which font face to load (default is first available face).
:param encoding: Which font encoding to use (default is Unicode). Possible
encodings include (see the FreeType documentation for more
information):
C:\Windows\Fonts
self.font = ImageFont.truetype("cambriab.ttf", size=35)
RGB
: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.pic_text)[0] # 获取字体宽度
h1 = self.font.getsize(self.pic_text)[1] # 获取字体高度
if
语句来实现: if self.p_flag == 1: # 左上角
location = (0, 0)
elif self.p_flag == 2: # 左下角
location = (0, h - h1)
elif self.p_flag == 3: # 右上角
location = (w - w1, 0)
elif self.p_flag == 4: # 右下角
location = (w - w1, h - h1)
elif self.p_flag == 5: # 居中
location = (h/2, h/2)
image_draw.text(location, self.pic_text, font=self.font, fill="blue")
transparent = new_img.split()[3]
transparent = ImageEnhance.Brightness(transparent).enhance(self.a)
new_img.putalpha(transparent)
Image.alpha_composite(image, new_img).save(img)
text_pic = TestText()
try:
file_list = os.listdir(text_pic.pic_path)
for i in range(0, len(file_list)):
filepath = os.path.join(text_pic.pic_path, file_list[i])
if os.path.isfile(filepath):
filetype = os.path.splitext(filepath)[1]
if filetype == '.png':
text_pic.test_text(filepath)
else:
print("图片格式有误,无法添加水印,请使用png格式图片")
print('批量添加水印完成')
except:
print('输入的文件路径有误,请检查~~')
# -*- coding:utf-8 -*-
# 作者:虫无涯
# 日期:2023/11/21
# 文件名称:test_text_pic.py
# 作用:批量给图片添加文字水印和图片水印
# 联系:VX(NoamaNelson)
# 博客:https://blog.csdn.net/NoamaNelson
from PIL import Image, ImageDraw, ImageFont, ImageEnhance
import os
class TestText():
def __init__(self):
super(TestText, self).__init__()
self.pic_path = input('图片路径:')
self.pic_text = input('水印文字:')
self.p_flag = int(input('水印位置(1:左上角,2:左下角,3:右上角,4:右下角,5:居中):'))
self.a = float(input('水印透明度(0—1之间的1位小数):'))
# 设置字体
self.font = ImageFont.truetype("cambriab.ttf", size=35)
# 文字水印
def test_text(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.pic_text)[0] # 字体宽度
h1 = self.font.getsize(self.pic_text)[1] # 字体高度
# 设置水印文字位置
if self.p_flag == 1: # 左上角
location = (0, 0)
elif self.p_flag == 2: # 左下角
location = (0, h - h1)
elif self.p_flag == 3: # 右上角
location = (w - w1, 0)
elif self.p_flag == 4: # 右下角
location = (w - w1, h - h1)
elif self.p_flag == 5: # 居中
location = (h/2, h/2)
# 绘制文字
image_draw.text(location, self.pic_text, font=self.font, fill="blue")
# 设置透明度
transparent = new_img.split()[3]
transparent = ImageEnhance.Brightness(transparent).enhance(self.a)
new_img.putalpha(transparent)
Image.alpha_composite(image, new_img).save(img)
if __name__ == "__main__":
text_pic = TestText()
try:
file_list = os.listdir(text_pic.pic_path)
for i in range(0, len(file_list)):
filepath = os.path.join(text_pic.pic_path, file_list[i])
if os.path.isfile(filepath):
filetype = os.path.splitext(filepath)[1]
if filetype == '.png':
text_pic.test_text(filepath)
print('批量添加水印完成')
except:
print('输入的文件路径有误,请检查~~')
D:\Python37\python.exe F:/python_study/python_project/test_text_pic.py
图片路径:F:\python_study\image\image01
水印文字:@虫无涯
水印位置(1:左上角,2:左下角,3:右上角,4:右下角,5:居中):1
水印透明度(0—1之间的1位小数):0.5
F:/python_study/python_project/test_text_pic.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.pic_text)[0] # 获取字体宽度
F:/python_study/python_project/test_text_pic.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.pic_text)[1] # 获取字体高度
批量添加水印完成