File size: 2,141 Bytes
ec9575a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e6c006b
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
# 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