RafaelJaime's picture
app add text to image, apply filter. Changed app, description and title in readme
9cfb783
raw
history blame
1.96 kB
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