File size: 4,074 Bytes
f6dcb1f
3778796
f6dcb1f
 
 
3778796
 
 
 
 
 
 
f6dcb1f
3778796
f6dcb1f
3778796
 
 
 
 
 
 
 
 
f6dcb1f
 
3778796
f6dcb1f
 
3778796
 
f6dcb1f
3778796
 
 
f6dcb1f
3778796
 
 
 
 
f6dcb1f
3778796
 
 
 
 
 
 
 
 
 
f6dcb1f
 
 
3778796
f6dcb1f
3778796
f6dcb1f
3778796
 
 
 
 
 
 
 
 
f6dcb1f
3778796
 
 
f6dcb1f
3778796
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f6dcb1f
 
3778796
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
import gradio as gr
import matplotlib.pyplot as plt
from io import BytesIO
from PIL import Image, ImageDraw, ImageFont

# Function to parse color
def parse_color(color):
    """Convert RGBA string to RGB tuple if necessary."""
    if isinstance(color, str) and color.startswith('rgba'):
        color = color.replace('rgba', '').strip('()').split(',')
        return tuple(int(float(c)) for c in color[:3])  # Convert to (R, G, B)
    return color  # If already valid, return as is

# Function to render plain text as an image
def render_plain_text_image(text, font_size, width, height, bg_color, text_color):
    """Convert plain text to an image with the given parameters."""
    bg_color = parse_color(bg_color)
    text_color = parse_color(text_color)

    # Create blank image
    img = Image.new("RGB", (width, height), color=bg_color)
    draw = ImageDraw.Draw(img)

    # Load font (default system font)
    try:
        font = ImageFont.truetype("arial.ttf", font_size)
    except:
        font = ImageFont.load_default()

    # Get text size
    text_width, text_height = draw.textsize(text, font=font)

    # Position text in center
    x = (width - text_width) // 2
    y = (height - text_height) // 2

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

    return img

# Function to render math (LaTeX) as an image
def render_math_image(text, font_size, width, height, bg_color, text_color):
    """Convert LaTeX-formatted text to an image."""
    fig, ax = plt.subplots(figsize=(width / 100, height / 100))
    ax.set_axis_off()

    # Ensure LaTeX formatting is correct
    if "$" in text:
        text = rf"{text}"

    ax.text(0.5, 0.5, text, fontsize=font_size, ha='center', va='center', color=text_color)

    buf = BytesIO()
    plt.savefig(buf, format='png', bbox_inches='tight', pad_inches=0.1)
    plt.close(fig)

    buf.seek(0)
    return Image.open(buf)

# Main function to handle input
def text_to_image(input_text, font_size, width, height, bg_color, text_color, mode):
    """Determine whether to use plain text or LaTeX rendering."""
    if mode == "Plain Text":
        return render_plain_text_image(input_text, font_size, width, height, bg_color, text_color)
    elif mode == "LaTeX Math":
        return render_math_image(input_text, font_size, width, height, bg_color, text_color)
    else:
        return "Invalid mode selected!"

# Function to handle file upload
def handle_file_upload(file, font_size, width, height, bg_color, text_color, mode):
    """Extract text from file and convert to an image."""
    if file is not None:
        text = file.read().decode("utf-8")  # Read and decode text file
        return text_to_image(text, font_size, width, height, bg_color, text_color, mode)
    return "No file uploaded!"

# Gradio Interface
with gr.Blocks() as demo:
    gr.Markdown("# 🖼️ Text to Image Converter")

    with gr.Row():
        input_text = gr.Textbox(label="Enter Text", placeholder="Type or paste text here...")
        file_input = gr.File(label="Upload a Text File", type="file")

    with gr.Row():
        font_size = gr.Slider(10, 100, value=30, label="Font Size")
        width = gr.Slider(200, 1000, value=500, label="Image Width")
        height = gr.Slider(200, 1000, value=300, label="Image Height")

    with gr.Row():
        bg_color = gr.ColorPicker(label="Background Color", value="#FFFFFF")
        text_color = gr.ColorPicker(label="Text Color", value="#000000")

    mode = gr.Radio(["Plain Text", "LaTeX Math"], label="Rendering Mode", value="Plain Text")

    output_image = gr.Image(label="Generated Image")

    convert_button = gr.Button("Convert Text to Image")
    file_convert_button = gr.Button("Convert File to Image")

    convert_button.click(
        text_to_image,
        inputs=[input_text, font_size, width, height, bg_color, text_color, mode],
        outputs=output_image
    )

    file_convert_button.click(
        handle_file_upload,
        inputs=[file_input, font_size, width, height, bg_color, text_color, mode],
        outputs=output_image
    )

demo.launch()