gaur3009 commited on
Commit
215c3c5
·
verified ·
1 Parent(s): 5551f75

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +32 -8
app.py CHANGED
@@ -16,19 +16,43 @@ def generate_text_image(text, style, width, height):
16
  draw = ImageDraw.Draw(img)
17
 
18
  # Dynamically calculate font size based on image dimensions
19
- font_size = int(min(width, height) * 0.1) # Adjust text to be proportional
20
  try:
21
  font = ImageFont.truetype(font_path[style], size=font_size)
22
  except:
23
  font = ImageFont.load_default()
24
 
25
- text_bbox = draw.textbbox((0, 0), text, font=font)
26
- text_width = text_bbox[2] - text_bbox[0]
27
- text_height = text_bbox[3] - text_bbox[1]
28
-
29
- position = ((width - text_width) // 2, (height - text_height) // 2)
30
-
31
- draw.text(position, text, font=font, fill=(0, 0, 0, 255))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
 
33
  return img
34
 
 
16
  draw = ImageDraw.Draw(img)
17
 
18
  # Dynamically calculate font size based on image dimensions
19
+ font_size = int(min(width, height) * 0.2) # Adjust text to be a larger proportion of the image
20
  try:
21
  font = ImageFont.truetype(font_path[style], size=font_size)
22
  except:
23
  font = ImageFont.load_default()
24
 
25
+ # Word wrapping to fit text within the image
26
+ max_width = width - 20 # Leave some padding
27
+ words = text.split()
28
+ lines = []
29
+ current_line = ""
30
+
31
+ for word in words:
32
+ test_line = f"{current_line} {word}".strip()
33
+ test_width, _ = draw.textsize(test_line, font=font)
34
+ if test_width <= max_width:
35
+ current_line = test_line
36
+ else:
37
+ lines.append(current_line)
38
+ current_line = word
39
+
40
+ if current_line:
41
+ lines.append(current_line)
42
+
43
+ # Calculate total text block height
44
+ line_height = draw.textsize("Test", font=font)[1]
45
+ total_text_height = line_height * len(lines)
46
+
47
+ # Start position for vertically centered text
48
+ y_position = (height - total_text_height) // 2
49
+
50
+ # Draw each line of text
51
+ for line in lines:
52
+ text_width, _ = draw.textsize(line, font=font)
53
+ x_position = (width - text_width) // 2
54
+ draw.text((x_position, y_position), line, font=font, fill=(0, 0, 0, 255))
55
+ y_position += line_height
56
 
57
  return img
58