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
| import os from PIL import Image from PIL import ImageDraw from PIL import ImageFont import random
FONT_PATH = "msyh.ttc" FONT_SIZE = 33 FONT_COLOR = (0, 0, 0, 20) ROTATE_ANGLE = 15 TEXT_STEP_X = 40 TEXT_STEP_Y = 20 IMAGE_PATH = "images" WATERMARK_TEXT = ["TXT", "..."] def Watermark(fname, text): try: font = ImageFont.truetype("msyh.ttc", FONT_SIZE) except IOError: print("字体文件没有找到,请检查字体路径") return try: img = Image.open(fname).convert('RGBA') except Exception as e: print(f"无法打开图片 {fname}: {e}") return text_overlay = Image.new("RGBA", img.size, (255, 255, 255, 0)) draw = ImageDraw.Draw(text_overlay) t = max(text) t_len = len(t) step_x = t_len * FONT_SIZE + TEXT_STEP_X step_y = t_len * FONT_SIZE // 2 + TEXT_STEP_Y for i in range(0, 2 * img.size[0] + 2 * step_x, step_x): for j in range(0, 2 * img.size[1] + 2 * step_y, step_y): draw.text((i, j), random.choice(text), font=font, fill=FONT_COLOR) text_overlay = text_overlay.rotate(ROTATE_ANGLE) image_with_text = Image.alpha_composite(img, text_overlay) output_dir = "output" if not os.path.exists(output_dir): os.makedirs(output_dir) output_path = os.path.join(output_dir, os.path.basename(fname)) image_with_text.save(output_path) print(f"Saved to {output_path}") def drawText(path, text): if not os.path.exists(path): print("没有这个路径:", path) return fileList = [os.path.join(fpathe, f) for fpathe, dirs, fs in os.walk(path) for f in fs if f.split(".")[-1].lower() in ["png", "jpg", "jpeg", "webp"] and not f.split(".")[0][-6:] == "marked"] for img in fileList: Watermark(img, text) if __name__ == '__main__': drawText(IMAGE_PATH, WATERMARK_TEXT)
|