File size: 1,698 Bytes
42718b0
 
 
2da0dea
42718b0
 
 
2da0dea
 
 
42718b0
2da0dea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image, ImageDraw, ImageFont

# Define the function to add text to the image
def add_text_to_image(image, text, text_color, text_size, text_position_x, text_position_y, font):
    # Convert the image to a PIL Image object if it's not already
    if isinstance(image, np.ndarray):
        image = Image.fromarray(image.astype('uint8'), 'RGB')
    
    # Create a drawing context
    draw = ImageDraw.Draw(image)
    
    # Load the font (you can specify a path to a .ttf file if needed)
    try:
        font = ImageFont.truetype(font, text_size)
    except IOError:
        # Fallback to a default font if the specified font is not available
        font = ImageFont.load_default()
    
    # Add the text to the image
    draw.text((text_position_x, text_position_y), text, fill=text_color, font=font)
    
    # Convert the image back to a numpy array for Gradio compatibility
    return np.array(image)

# Gradio interface
iface = gr.Interface(
    fn=add_text_to_image,
    inputs=[
        gr.Image(label="Input Image"),
        gr.Textbox(label="Text"),
        gr.ColorPicker(label="Text Color", value="#FFFFFF"),
        gr.Slider(minimum=10, maximum=100, value=30, label="Text Size"),
        gr.Slider(minimum=0, maximum=500, value=50, label="Text Position X"),
        gr.Slider(minimum=0, maximum=500, value=50, label="Text Position Y"),
        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 and add customizable text to it."
)

# Launch the Gradio app
iface.launch()