Spaces:
Sleeping
Sleeping
import streamlit as st | |
from PIL import Image, ImageDraw, ImageFont | |
import io | |
# Set up the app | |
def main(): | |
st.title("Text to Image Converter") | |
st.write("Enter text to generate an image containing the text.") | |
# User input | |
user_text = st.text_input("Enter your text:") | |
if st.button("Generate Image"): | |
if user_text.strip(): | |
# Generate image with text | |
img = create_text_image(user_text) | |
st.image(img, caption="Generated Image", use_container_width=True) | |
else: | |
st.warning("Please enter some text before generating an image.") | |
def create_text_image(text): | |
# Create a blank image with white background | |
width, height = 800, 400 | |
img = Image.new("RGB", (width, height), color="white") | |
draw = ImageDraw.Draw(img) | |
# Load a font (default font if custom fonts aren't available) | |
try: | |
font = ImageFont.truetype("arial.ttf", size=36) | |
except IOError: | |
font = ImageFont.load_default() | |
# Calculate text position to center it using textbbox | |
text_bbox = draw.textbbox((0, 0), text, font=font) | |
text_width, text_height = text_bbox[2] - text_bbox[0], text_bbox[3] - text_bbox[1] | |
text_x = (width - text_width) // 2 | |
text_y = (height - text_height) // 2 | |
# Draw text on the image | |
draw.text((text_x, text_y), text, fill="black", font=font) | |
# Convert to BytesIO for display | |
img_byte_arr = io.BytesIO() | |
img.save(img_byte_arr, format="PNG") | |
img_byte_arr.seek(0) | |
return img_byte_arr | |
# Run the app | |
if __name__ == "__main__": | |
main() | |