由于工作需要,需要向图片内插入指定密度的水印图,但是发现网上的代码都是向图片里插入文字水印,所以通过插文字水印的思路写了一个插入水印图的程序。
import os
from PIL import Image
#文件夹路径
filePathchoose = 'E:/get_picture/picture'
print(filePathchoose)
#行列数密度
Hang = 2
Lie = 2
#水印参数
shuiyin_path = './2.png'
shuiyin = Image.open(shuiyin_path)
shui_w = int(shuiyin.size[0])
shui_h = int(shuiyin.size[1])
#水印合成
def Picture_Synthesis(M_Img, son_img,shui_w, shui_h, coordinate):
S_Img = Image.open(son_img).convert('RGBA')
# # 重新设置子图的尺寸
icon = S_Img.resize((shui_w, shui_h), Image.ANTIALIAS)
try:
# print("已经指定坐标")
M_Img.paste(icon, coordinate, mask=None)
except:
print("坐标指定出错 ")
# 保存图片
return M_Img
###程序主干
for root, dirs, files in os.walk(filePathchoose, topdown=True):
for name in files:
if '.jpg' in name:
imagePath = os.path.join(root, name) # 图片地址
print(imagePath)
try:
img = Image.open(imagePath) # 读取照片
image_null = Image.new('RGBA', img.size, (0, 0, 0, 0))
except:
continue
# 打印图片大小
print(img.size)
width = int(img.size[0]) # 长度
height = int(img.size[1]) # 宽度
#判断是否超限
if shui_w * Lie > width:
Hang = int(width // shui_w)
if shui_h * Lie > height:
Lie = int(height // shui_h)
#插入水印图
if Hang == 1:
if Lie == 1:
x1 = int((width - shui_w) // 2)
y1 = int((height - shui_h) // 2)
image_null = Picture_Synthesis(image_null, shuiyin_path, shui_w, shui_h, coordinate=(x1, y1))
else:
for j in range(0, Lie):
x1 = int((width - shui_w) // 2)
y1 = int(j * height // Lie)
image_null = Picture_Synthesis(image_null, shuiyin_path, shui_w, shui_h, coordinate=(x1, y1))
else:
if Lie == 1:
for i in range(0, Hang):
x1 = int(i * width // Hang)
y1 = int((height - shui_h) // 2)
image_null = Picture_Synthesis(image_null, shuiyin_path, shui_w, shui_h, coordinate=(x1, y1))
else:
for i in range(0, Hang):
for j in range(0, Lie):
x1 = int(i * width // Hang)
y1 = int(j * height // Lie)
image_null = Picture_Synthesis(image_null, shuiyin_path, shui_w, shui_h, coordinate=(x1, y1))
try:
img_PIL = img.convert('RGBA')
res_image = Image.alpha_composite(img_PIL, image_null)
res_image = res_image.convert('RGB')
res_image.save(imagePath)
print('SUCCESS')
print("********************")
except:
pass



