T2I / app.py
VirtualOasis's picture
Update app.py
4eeb4da verified
raw
history blame
2.96 kB
import gradio as gr
from PIL import Image, ImageDraw, ImageFont
import textwrap
import io
import os
def text_to_image(text_content):
"""
Convert text content to a formatted image with fixed styling.
Args:
text_content (str): The input text to convert to image
Returns:
PIL.Image: Generated image
"""
if not text_content.strip():
text_content = "Please enter some text to convert to image."
# Fixed styling parameters
img_width = 600 # 3:4 ratio width
img_height = 800 # 3:4 ratio height
background_color = "#F8F9FA" # Light theme background
text_color = "#000000" # Black text
padding = 40
font_size = 24 # Medium font size
line_spacing = 8
# Create image
img = Image.new('RGB', (img_width, img_height), background_color)
draw = ImageDraw.Draw(img)
# Try to use a nice font, fallback to default if not available
try:
font = ImageFont.truetype("/System/Library/Fonts/Arial.ttf", font_size)
except:
try:
font = ImageFont.truetype("arial.ttf", font_size)
except:
font = ImageFont.load_default()
# Calculate text area
text_width = img_width - (padding * 2)
# Wrap text to fit width
chars_per_line = text_width // (font_size // 2) # Rough estimate
wrapped_lines = []
paragraphs = text_content.split('\n')
for paragraph in paragraphs:
if paragraph.strip():
lines = textwrap.wrap(paragraph, width=chars_per_line)
wrapped_lines.extend(lines)
wrapped_lines.append("") # Add space between paragraphs
else:
wrapped_lines.append("")
# Remove trailing empty lines
while wrapped_lines and wrapped_lines[-1] == "":
wrapped_lines.pop()
# Draw text
y_position = padding
for line in wrapped_lines:
if y_position + font_size > img_height - padding:
# Add "..." if text is too long
draw.text((padding, y_position), "...", font=font, fill=text_color)
break
draw.text((padding, y_position), line, font=font, fill=text_color)
y_position += font_size + line_spacing
return img
demo = gr.Interface(
fn=text_to_image,
inputs=[gr.Textbox(
label="Text Content",
placeholder="Enter your text content here...",
lines=10,
value="Welcome to Text-to-Image Converter!\n\nThis tool converts your text into beautifully formatted images perfect for social media posts.\n\nSimply replace this text with your content and click generate!"
)],
outputs=[gr.Image(label="Generated Image", type="pil")],
title="Text to Image Converter",
description="Convert your text content into attractive images with a clean, readable design. Perfect for social media posts and content sharing!"
)
if __name__ == "__main__":
demo.launch(mcp_server=True)