Вроде так:
from PIL import Image, ImageDraw, ImageFont
def create_advertisement_image(text, output_path="advertisement.png"):
if 'Жену' in text:
background_color = '#c02d23'
text_color = '#fafeff'
shadow_color = '#9b0a1f'
elif 'Мужа' in text:
background_color = '#7e4db8'
text_color = '#fafeff'
shadow_color = '#67418e'
else:
background_color = '#FFE8B7'
text_color = '#5E0D26'
shadow_color = '#9b0a1f'
image = Image.new('RGB', (1080, 1080), color=background_color)
draw = ImageDraw.Draw(image)
try:
font_regular = ImageFont.truetype('Nunito-Black.ttf', size=50)
font_large = ImageFont.truetype('Nunito-Black.ttf', size=80)
except IOError:
print("Ошибка загрузки шрифта. Используется шрифт по умолчанию.")
font_regular = ImageFont.load_default()
font_large = ImageFont.load_default()
margin = 50
text_position = (margin, margin)
parts = text.split(':')
colored_text = []
for i, part in enumerate(parts):
colored_text.append(part)
if i < len(parts) - 1:
colored_text.append(':')
current_position = text_position
for part in colored_text:
if part == ':':
draw.text((current_position[0] + 6, current_position[1] + 6), part, font=font_regular, fill=shadow_color)
draw.text(current_position, part, font=font_regular, fill='yellow')
else:
draw.text((current_position[0] + 6, current_position[1] + 6), part, font=font_regular, fill=shadow_color)
draw.text(current_position, part, font=font_regular, fill=text_color)
current_position = (current_position[0] + draw.textsize(part, font=font_regular)[0], current_position[1])
image.save(output_path)
with open('your_text_file.txt', 'r', encoding='utf-8') as file:
text = file.read()
create_advertisement_image(text)