MagicFaceTG / utils.py
rastof9's picture
Update Gradio app with multiple files
e6c006b verified
# utils.py
import logging
from PIL import Image, ImageDraw, ImageFont
logger = logging.getLogger(__name__)
def add_watermark(image_path: str, watermark_text: str) -> str:
"""
Adds a text watermark to an image and saves it over the original file.
Args:
image_path (str): The path to the input image.
watermark_text (str): The text to use for the watermark.
Returns:
str: The path to the watermarked image (same as input).
"""
try:
with Image.open(image_path).convert("RGBA") as base:
# Create a transparent layer for the text
txt_layer = Image.new("RGBA", base.size, (255, 255, 255, 0))
# Choose a font
try:
# Use a common system font if available
font = ImageFont.truetype("arial.ttf", 40)
except IOError:
# Use a default font if the specific one isn't found
logger.warning("Arial font not found. Using default PIL font.")
font = ImageFont.load_default()
# Get a drawing context
d = ImageDraw.Draw(txt_layer)
# Calculate the x,y coordinates of the text
# We'll place it in the bottom right corner
width, height = base.size
textwidth, textheight = d.textbbox((0, 0), watermark_text, font=font)[2:]
x = width - textwidth - 10
y = height - textheight - 10
# Draw text with a semi-transparent white color
d.text((x, y), watermark_text, font=font, fill=(255, 255, 255, 128))
# Composite the text layer over the base image
out = Image.alpha_composite(base, txt_layer)
# Convert back to RGB and save over the original file
out.convert("RGB").save(image_path, "PNG")
logger.info(f"Watermark '{watermark_text}' added to {image_path}")
return image_path
except Exception as e:
logger.error(f"Failed to add watermark to {image_path}: {e}")
# Return the original path even if watermarking fails
return image_path