File size: 2,036 Bytes
d4174bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from PIL import Image, ImageDraw, ImageFont
import os
from typing import Optional, Tuple, Dict, Any

def add_text_to_image(
    image_path: str,
    text: str,
    color: Optional[Tuple[int, int, int]] = None,
    output_name: Optional[str] = None
) -> Dict[str, Any]:
    """
    Adds centered text to an image and saves the result in the same folder.
    If no output_name is provided, '_edited' is appended to the original filename.
    If no color is provided, black is used by default.

    Args:
        image_path: Path to the original image.
        text: Text to write on the image.
        color: Optional RGB color of the text. Defaults to black.
        output_name: Optional output filename (without extension).

    Returns:
        Dictionary with success status and info.
    """
    try:
        if color is None:
            color = (0, 0, 0)

        image = Image.open(image_path)
        draw = ImageDraw.Draw(image)
        font = ImageFont.load_default()

        text_width = draw.textlength(text, font=font)
        x = (image.width - text_width) / 2
        y = image.height / 2

        draw.text((x, y), text, fill=color, font=font)

        base_dir = os.path.dirname(image_path)
        base_name, ext = os.path.splitext(os.path.basename(image_path))

        if output_name:
            new_filename = f"{output_name}{ext}"
        else:
            new_filename = f"{base_name}_edited{ext}"

        new_path = os.path.join(base_dir, new_filename)

        image.save(new_path)
        output_size = os.path.getsize(new_path)

        return {
            "success": True,
            "message": "Text added successfully to the image",
            "input_path": image_path,
            "output_path": new_path,
            "output_size_bytes": output_size,
            "text": text,
            "color": color
        }

    except Exception as e:
        return {
            "success": False,
            "error": str(e),
            "input_path": image_path,
            "output_path": None
        }