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
|
from PIL import Image, ImageDraw, ImageFont import os import configparser
def read_config(ini_path): config = configparser.ConfigParser() config.read(ini_path)
watermark_text = config['diy']['text'] font_path = config['diy']['path'] font_color = tuple(map(int, config['diy']['color'].split(','))) font_size = int(config['diy']['size']) position = tuple(map(int, config['diy']['xy'].split(','))) output = config['diy']['out']
return watermark_text, font_path, font_color, font_size, position, output
def add_watermark_to_gif(gif_path, watermark_text, output_path, font_path, font_color, font_size, position): with Image.open(gif_path) as gif: if gif.is_animated: frames = [] durations = [] for i in range(gif.n_frames): gif.seek(i) frame = gif.copy().convert("RGBA") frames.append(frame) durations.append(gif.info['duration'])
watermarked_frames = [] for frame in frames: draw = ImageDraw.Draw(frame) font = ImageFont.truetype(font_path, font_size)
draw.text(position, watermark_text, fill=font_color, font=font) watermarked_frames.append(frame)
watermarked_gif = frames[0] watermarked_gif.save( output_path, save_all=True, append_images=watermarked_frames[1:], durations=durations, loop=0 ) else: with Image.open(gif_path) as img: img = img.convert("RGBA") draw = ImageDraw.Draw(img) font = ImageFont.truetype(font_path, font_size) draw.text(position, watermark_text, fill=font_color, font=font) img.save(output_path)
def batch_add_watermark_to_gifs(gif_folder, ini_path): watermark_text, font_path, font_color, font_size, position, output = read_config(ini_path)
if not os.path.exists(output): os.makedirs(output)
for filename in os.listdir(gif_folder): if filename.lower().endswith('.gif'): input_path = os.path.join(gif_folder, filename) output_path = os.path.join(output, filename) add_watermark_to_gif(input_path, watermark_text, output_path, font_path, font_color, font_size, position)
print(f"{filename}")
batch_add_watermark_to_gifs('input', 'user.ini')
print('图片已批量处理完成!')
|