本案例主要是通过python实现批量给图片添加水印的功能。使用标准库os,第三方库pillow。
给定文件夹及水印图如下:
import os
from PIL import Image
def watermark_photo(input_image_path,watermark_image_path,output_image_path):
# 水印功能实现主函数
# input_image_path: 输入图片路径 watermark_image_path:水印路径,output_image_path:输出图片路径
base_image = Image.open(input_image_path)
watermark = Image.open(watermark_image_path).convert("RGBA")
# 添加水印到给定图片
position = base_image.size
newsize = (int(position[0]*8/100),int(position[0]*8/100))
# 图片缩放
watermark = watermark.resize(newsize)
# 设定新的水印位置,参数可自调
new_position = position[0]-newsize[0]-20,position[1]-newsize[1]-20
# 创建新的空白图像
transparent = Image.new(mode='RGBA',size=position,color=(0,0,0,0))
# 粘贴原始图像
transparent.paste(base_image,(0,0))
# 粘贴水印图像
transparent.paste(watermark,new_position,watermark)
image_mode = base_image.mode
# 判断图片的模式是否是'RGB'
if image_mode == 'RGB':
transparent = transparent.convert(image_mode)
else:
transparent = transparent.convert('P')
transparent.save(output_image_path,optimize=True,quality=100)
print("Saving"+output_image_path+"...")
# 输入文件夹及水印图完整地址
folder = input("输入文件夹路径:")
watermark = input("输入水印完整路径:")
os.chdir(folder)
files = os.listdir(os.getcwd())
if not os.path.isdir("output"):
os.mkdir("output")
for f in files:
if os.path.isfile(os.path.abspath(f)):
if f.endswith(".png") or f.endswith(".jpg"):
watermark_photo(f,watermark,"output/"+f)