|
import gradio as gr |
|
import numpy as np |
|
from PIL import Image, ImageDraw, ImageFont |
|
|
|
|
|
COLOR_MAP = { |
|
"white": (255, 255, 255), |
|
"black": (0, 0, 0), |
|
"red": (255, 0, 0), |
|
"green": (0, 255, 0), |
|
"blue": (0, 0, 255), |
|
"yellow": (255, 255, 0), |
|
"cyan": (0, 255, 255), |
|
"magenta": (255, 0, 255), |
|
} |
|
|
|
|
|
def add_text_to_image(image, text, text_color, text_size, width, height, text_align, font): |
|
try: |
|
|
|
if isinstance(image, np.ndarray): |
|
image = Image.fromarray(image.astype('uint8'), 'RGB') |
|
|
|
|
|
original_width, original_height = image.size |
|
aspect_ratio = original_width / original_height |
|
|
|
|
|
if width / height > aspect_ratio: |
|
new_width = int(height * aspect_ratio) |
|
new_height = height |
|
else: |
|
new_width = width |
|
new_height = int(width / aspect_ratio) |
|
|
|
|
|
image = image.resize((new_width, new_height), Image.Resampling.LANCZOS) |
|
|
|
|
|
new_image = Image.new("RGB", (width, height), (255, 255, 255)) |
|
|
|
new_image.paste(image, ((width - new_width) // 2, (height - new_height) // 2)) |
|
|
|
|
|
draw = ImageDraw.Draw(new_image) |
|
|
|
|
|
try: |
|
font = ImageFont.truetype(font, text_size) |
|
except IOError: |
|
|
|
font = ImageFont.load_default() |
|
|
|
|
|
color_rgb = COLOR_MAP.get(text_color, (255, 255, 255)) |
|
|
|
|
|
text_width, text_height = draw.textsize(text, font=font) |
|
if text_align == "left": |
|
text_position_x = 10 |
|
elif text_align == "right": |
|
text_position_x = width - text_width - 10 |
|
elif text_align == "center": |
|
text_position_x = (width - text_width) // 2 |
|
|
|
text_position_y = (height - text_height) // 2 |
|
|
|
|
|
draw.text((text_position_x, text_position_y), text, fill=color_rgb, font=font) |
|
|
|
|
|
return np.array(new_image) |
|
|
|
except Exception as e: |
|
|
|
print(f"Error: {e}") |
|
return None |
|
|
|
|
|
iface = gr.Interface( |
|
fn=add_text_to_image, |
|
inputs=[ |
|
gr.Image(label="Input Image"), |
|
gr.Textbox(label="Text"), |
|
gr.Dropdown(label="Text Color", choices=list(COLOR_MAP.keys()), value="white"), |
|
gr.Slider(minimum=10, maximum=100, value=30, label="Text Size"), |
|
gr.Slider(minimum=100, maximum=2048, value=1024, label="Width"), |
|
gr.Slider(minimum=100, maximum=2048, value=1024, label="Height"), |
|
gr.Dropdown(label="Text Alignment", choices=["left", "right", "center"], value="center"), |
|
gr.Textbox(label="Font (e.g., 'arial.ttf')", value="arial.ttf") |
|
], |
|
outputs=gr.Image(label="Output Image"), |
|
title="Add Text to Image", |
|
description="Upload an image, resize it, and add customizable text with alignment options." |
|
) |
|
|
|
|
|
iface.launch() |