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
| import os from PIL import Image
def add_fullscreen_watermark(input_dir, watermark_path, output_dir, opacity=0.15): if not os.path.exists(output_dir): os.makedirs(output_dir)
try: original_watermark = Image.open(watermark_path).convert("RGBA") except Exception as e: print(f"Error: Could not open watermark image: {e}") return
r, g, b, a = original_watermark.split() a = a.point(lambda p: p * opacity) original_watermark.putalpha(a)
valid_extensions = ('.png', '.jpg', '.jpeg', '.bmp')
for filename in os.listdir(input_dir): if filename.lower().endswith(valid_extensions): img_path = os.path.join(input_dir, filename) try: base_image = Image.open(img_path).convert("RGBA") img_w, img_h = base_image.size combined = Image.new('RGBA', base_image.size, (0, 0, 0, 0)) combined.paste(base_image, (0, 0))
wm_orig_w, wm_orig_h = original_watermark.size target_wm_w = img_w target_wm_h = int(wm_orig_h * (target_wm_w / wm_orig_w)) try: resample_filter = Image.Resampling.LANCZOS except AttributeError: resample_filter = Image.LANCZOS watermark_scaled = original_watermark.resize((target_wm_w, target_wm_h), resample_filter)
y_offset = 0 while y_offset < img_h: combined.paste(watermark_scaled, (0, y_offset), mask=watermark_scaled) y_offset += target_wm_h
output_path = os.path.join(output_dir, filename) if filename.lower().endswith(('.jpg', '.jpeg')): combined.convert("RGB").save(output_path, quality=95) else: combined.save(output_path) print(f"Successfully processed: {filename}") except Exception as e: print(f"Error processing {filename}: {e}")
if __name__ == "__main__": INPUT_DIR = r"这个是需要加水印的图片所在的绝对路径" WATERMARK_PATH = r"这个是水印图片的绝对路径" OUTPUT_DIR = os.path.join(INPUT_DIR, "watermarked")
add_fullscreen_watermark(INPUT_DIR, WATERMARK_PATH, OUTPUT_DIR, opacity=0.15) print("\nAll tasks completed! Long images have been tiled instead of stretched.")
|