IFRAME SYNC
from PIL import Image, ImageDraw, ImageFont
def text_to_image(text, output_image_path='output_image.png', font_size=20, image_size=(500, 500)):
# Create a blank image with a white background
image = Image.new('RGB', image_size, color='white')
# Choose a font and size
font = ImageFont.truetype('arial.ttf', font_size)
# Create a drawing object
draw = ImageDraw.Draw(image)
# Define text color
text_color = 'black'
# Calculate text position
text_width, text_height = draw.textsize(text, font)
x = (image_size[0] - text_width) // 2
y = (image_size[1] - text_height) // 2
# Draw the text on the image
draw.text((x, y), text, font=font, fill=text_color)
# Save the image
image.save(output_image_path)
if __name__ == '__main__':
# Example usage
input_text = "Hello, this is a text to image example!"
output_image_path = "output_image.png"
text_to_image(input_text, output_image_path)
print(f"Image saved to {output_image_path}")from PIL import Image, ImageDraw, ImageFont
import os
def text_to_image(text, output_image_path='output_image.png', font_size=20, image_size=(500, 500),
font_color='black', background_color='white', font_path=None):
# Create a blank image with a specified background color
image = Image.new('RGB', image_size, color=background_color)
# Choose a font and size
if font_path is None:
font = ImageFont.load_default()
else:
if not os.path.isfile(font_path):
raise FileNotFoundError(f"Font file not found: {font_path}")
font = ImageFont.truetype(font_path, font_size)
# Create a drawing object
draw = ImageDraw.Draw(image)
# Calculate text position
text_width, text_height = draw.textsize(text, font)
x = (image_size[0] - text_width) // 2
y = (image_size[1] - text_height) // 2
# Draw the text on the image
draw.text((x, y), text, font=font, fill=font_color)
# Save the image
image.save(output_image_path)
if __name__ == '__main__':
try:
input_text = input("Enter the text: ")
output_image_path = input("Enter the output image path (e.g., output_image.png): ")
font_size = int(input("Enter the font size: "))
font_color = input("Enter the font color (e.g., 'black', 'red', '#00FF00'): ")
background_color = input("Enter the background color (e.g., 'white', 'blue', '#FFFF00'): ")
font_path = input("Enter the path to the font file (leave empty for default): ")
text_to_image(input_text, output_image_path, font_size, font_color=font_color,
background_color=background_color, font_path=font_path)
print(f"Image saved to {output_image_path}")
except Exception as e:
print(f"An error occurred: {e}")
IFRAME SYNC
Comments
Post a Comment