1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
| import os import glob from PIL import Image, ImageDraw, ImageFont
def ensure_directory(directory): """ 确保指定的目录存在,如果不存在则创建。 :param directory: 要确保存在的目录路径。 """ if not os.path.exists(directory): os.makedirs(directory)
def calculate_font_size(image_width): """ 根据图像宽度计算字体大小。 :param image_width: 图像的宽度。 :return: 字体大小。 """ return int(image_width / 20)
def add_watermark(image_path, watermark_text, output_dir): image = Image.open(image_path).convert("RGBA") txt_layer = Image.new("RGBA", image.size, (255, 255, 255, 0))
font_size = calculate_font_size(image.width) try: font = ImageFont.truetype("arial.ttf", size=font_size) except IOError: font = ImageFont.load_default()
draw = ImageDraw.Draw(txt_layer) lines = watermark_text.split("\n") total_height = 0 max_width = 0
for line in lines: bbox = draw.textbbox((0, 0), line, font=font) text_width = bbox[2] - bbox[0] text_height = bbox[3] - bbox[1] total_height += text_height max_width = max(max_width, text_width)
width, height = image.size margin = 10 x = width - max_width - margin y = height - total_height - margin
watermark_color = (125, 38, 205, 128)
for i, line in enumerate(lines): bbox = draw.textbbox((0, 0), line, font=font) text_width = bbox[2] - bbox[0] text_height = bbox[3] - bbox[1] draw.text((x + (max_width - text_width), y + i * text_height - 30), line, font=font, fill=watermark_color)
combined = Image.alpha_composite(image, txt_layer)
combined = combined.convert("RGB")
filename = os.path.basename(image_path) output_path = os.path.join(output_dir, filename)
combined.save(output_path) print(f"Processed and saved {output_path}")
def update_img(dir, water_name, output_dir): ensure_directory(output_dir) for img_name_dir in dir: add_watermark(img_name_dir, water_name, output_dir)
if __name__ == '__main__': script_dir = os.getcwd() output_dir = os.path.join(script_dir, "shuiyin_img") for key in ['webp', 'png', 'jpg', 'jpeg']: image_list = glob.iglob(rf"C:\newBlog\新建文件夹\*.{key}", recursive=True) update_img(dir=image_list, water_name="jerryWang", output_dir=output_dir)
|