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

def parse_color(color_str):
    if color_str.startswith('rgba('):
        values = color_str[5:-1].split(',')
        r = int(float(values[0]))
        g = int(float(values[1]))
        b = int(float(values[2]))
        return (r, g, b)
    elif color_str.startswith('rgb('):
        values = color_str[4:-1].split(',')
        r = int(float(values[0]))
        g = int(float(values[1]))
        b = int(float(values[2]))
        return (r, g, b)
    elif color_str.startswith('#'):
        return color_str
    else:
        return color_str

def add_text_to_image_base64(image, text, x, y, font_size, color, centered=False):
    """
    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.
    """
    if image is None:
        return None
    
    img = image.copy()
    draw = ImageDraw.Draw(img)
    
    try:
        font = ImageFont.truetype("arial.ttf", font_size)
    except:
        try:
            font = ImageFont.truetype("/System/Library/Fonts/Arial.ttf", font_size)
        except:
            font = ImageFont.load_default()
    
    parsed_color = parse_color(color)
    
    if centered:
        bbox = draw.textbbox((0, 0), text, font=font)
        text_width = bbox[2] - bbox[0]
        text_height = bbox[3] - bbox[1]
        x = (img.width - text_width) // 2
        y = (img.height - text_height) // 2
    
    draw.text((x, y), text, fill=parsed_color, font=font)
    return img