Spaces:
Sleeping
Sleeping
| 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 = 55 | |
| 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().startswith("#") and (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) |