[Python] 纯文本查看 复制代码
import os
from PIL import Image, ImageEnhance
from tkinter import Tk, filedialog, Label, Entry, Button, StringVar, IntVar, messagebox
def add_watermark(input_folder, watermark_path, output_folder, position, transparency):
watermark = Image.open(watermark_path).convert("RGBA")
alpha = watermark.split()[3]
alpha = ImageEnhance.Brightness(alpha).enhance(transparency / 100.0)
watermark.putalpha(alpha)
for filename in os.listdir(input_folder):
if filename.endswith(('.png', '.jpg', '.jpeg')):
image_path = os.path.join(input_folder, filename)
image = Image.open(image_path).convert("RGBA")
if position == "左上角":
position = (0, 0)
elif position == "右上角":
position = (image.width - watermark.width, 0)
elif position == "左下角":
position = (0, image.height - watermark.height)
elif position == "右下角":
position = (image.width - watermark.width, image.height - watermark.height)
image.paste(watermark, position, mask=watermark)
output_path = os.path.join(output_folder, filename)
image.save(output_path, 'PNG')
messagebox.showinfo("完成", "所有图片已成功添加水印!")
def select_folder():
root = Tk()
root.withdraw()
folder_selected = filedialog.askdirectory()
root.destroy()
return folder_selected
def main():
root = Tk()
root.title("批量添加水印")
Label(root, text="输入文件夹路径:").grid(row=0, column=0)
input_folder = StringVar()
Entry(root, textvariable=input_folder, width=50).grid(row=0, column=1)
Button(root, text="选择", command=lambda: input_folder.set(select_folder())).grid(row=0, column=2)
Label(root, text="水印文件路径:").grid(row=1, column=0)
watermark_path = StringVar()
Entry(root, textvariable=watermark_path, width=50).grid(row=1, column=1)
Button(root, text="选择", command=lambda: watermark_path.set(filedialog.askopenfilename())).grid(row=1, column=2)
Label(root, text="输出文件夹路径:").grid(row=2, column=0)
output_folder = StringVar()
Entry(root, textvariable=output_folder, width=50).grid(row=2, column=1)
Button(root, text="选择", command=lambda: output_folder.set(select_folder())).grid(row=2, column=2)
Label(root, text="水印位置:").grid(row=3, column=0)
position = StringVar()
position.set("右下角")
Entry(root, textvariable=position, width=10).grid(row=3, column=1)
Label(root, text="透明度(%):").grid(row=4, column=0)
transparency = IntVar()
transparency.set(100)
Entry(root, textvariable=transparency, width=10).grid(row=4, column=1)
Button(root, text="开始处理", command=lambda: add_watermark(input_folder.get(), watermark_path.get(), output_folder.get(), position.get(), transparency.get())).grid(row=5, columnspan=3)
root.mainloop()
if __name__ == "__main__":
main()