File size: 2,593 Bytes
71970fd bf09443 71970fd fd666eb 71970fd bf09443 71970fd bf09443 71970fd bf09443 4f0f4ad bf09443 71970fd bf09443 71970fd bf09443 71970fd bf09443 71970fd bf09443 71970fd 4f0f4ad 71970fd 4f0f4ad 71970fd bf09443 4f0f4ad bf09443 23d2cab 4f0f4ad bf09443 fd666eb bf09443 |
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 |
from PIL import Image, ImageDraw, ImageFont
import os
IMAGE_DIR = "/tmp/images"
os.makedirs(IMAGE_DIR, exist_ok=True)
def get_text_size(text, font):
bbox = font.getbbox(text)
width = bbox[2] - bbox[0]
height = bbox[3] - bbox[1]
return width, height
def create_text_image(text,id,image_olst, image_size=(1280, 720), bg_color="white", text_color="black"):
image = Image.new("RGB", image_size, color=bg_color)
draw = ImageDraw.Draw(image)
font_path = "/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf"
bold_font_path = "/usr/share/fonts/truetype/liberation/LiberationSans-Bold.ttf"
max_font_size = 65
min_font_size = 10
best_font = None
best_lines = []
for font_size in range(max_font_size, min_font_size, -2):
font = ImageFont.truetype(font_path, font_size)
words = text.split()
lines = []
current_line = ""
lines_raw = text.splitlines()
lines = []
for raw_line in lines_raw:
words = raw_line.split()
current_line = ""
left_padding = 80
right_padding = 80
max_text_width = image_size[0] - left_padding - right_padding
for word in words:
test_line = f"{current_line} {word}" if current_line else word
w, _ = get_text_size(test_line, font)
if w <= max_text_width:
current_line = test_line
else:
lines.append(current_line)
current_line = word
if current_line:
lines.append(current_line)
total_height = sum(get_text_size(line, font)[1] + 23 for line in lines)
if total_height <= image_size[1] * 0.95:
best_font = font
best_lines = lines
break
heading_color = "#0033cc" # Deep attractive blue
normal_color = text_color # Usually black
y = (image_size[1] - total_height) // 2
for line in best_lines:
is_heading = line.strip().endswith("?") or line.strip().endswith(":")
font_to_use = ImageFont.truetype(bold_font_path, best_font.size) if is_heading else best_font
color_to_use = heading_color if is_heading else normal_color
w, h = get_text_size(line, font_to_use)
x = 80 # Left padding
draw.text((x, y), line, font=font_to_use, fill=color_to_use)
y += h + 23
image_name="slide"+str(id)+".png"
image_olst.append(image_name)
image_path=os.path.join(IMAGE_DIR,image_name)
image.save(image_path)
|