该程序的功能是,批量给图片打水印,水印居中显示,默认透明度50%
废话不多说直接上代码
from PIL import Image
import os
# 图片输入路径
input_dir = 'img\\'
# 图片输出路径
output_dir = 'res\\'
# 水印文件
watermark_file = 's.png'
# 水印透明度
transparency = 0.5
# 水印和图片的比例
watermark_scale = 2
if not os.path.isdir(input_dir):
print('当前目录没有找到输入文件夹:img\\')
exit()
if not os.path.isdir(output_dir):
os.mkdir(output_dir)
if not os.path.exists(watermark_file):
print('当前目录没有找到水印文件:s.png')
def add_watermark(img_file):
global input_dir
global output_dir
global watermark_file
global transparency
global watermark_scale
file_ex = os.path.splitext(img_file)[1].lower()
if file_ex!='.jpg' and file_ex!='.bmp' and file_ex!='.jpeg' and file_ex!='.png':
print("不支持",img_file,"文件格式,只支持jpg bmp jpeg png")
return
print("正在处理", img_file)
img_file_path = os.path.join(input_dir, img_file)
img = Image.open(img_file_path)
img_w, img_h = img.size
watermark_img = Image.open(watermark_file)
watermark_w, watermark_h = watermark_img.size
if watermark_w*watermark_scale>img_w or watermark_h*watermark_scale>img_h:
resize_scale = 1
if img_h/watermark_h>img_w/watermark_w:
resize_scale=watermark_w/(img_w/watermark_scale)
else:
resize_scale=watermark_h/(img_h/watermark_scale)
dst_w = int(watermark_w//resize_scale)
dst_h = int(watermark_h//resize_scale)
watermark_img = watermark_img.resize((dst_w,dst_h))
watermark_h, watermark_w = dst_h, dst_w
pos_y = (img_h - watermark_h)//2
pos_x = (img_w - watermark_w)//2
watermark_overlay = Image.new('RGBA', img.size, (255, 255, 255, 0))
watermark_overlay.paste(watermark_img,(pos_x,pos_y))
# 设置每个像素点颜色的透明度
for x in range(watermark_overlay.size[0]):
for y in range(watermark_overlay.size[1]):
color = watermark_overlay.getpixel((x, y))
if color[3]>0:
color = (color[0],color[1],color[2],int(color[3]*transparency))
watermark_overlay.putpixel((x, y), color)
rgba_image = img.convert('RGBA')
res_img = Image.alpha_composite(rgba_image, watermark_overlay)
output_file = os.path.join(output_dir, img_file)
if file_ex!='.png':
res_img = res_img.convert('RGB')
res_img.save(output_file)
for img_file in os.listdir(input_dir):
add_watermark(img_file)