55class ComputerTextGenerator (object ):
66 @classmethod
77 def generate (cls , text , font , text_color , font_size , orientation , space_width ):
8+ if orientation == 0 :
9+ return cls .__generate_horizontal_text (text , font , text_color , font_size , space_width )
10+ elif orientation == 1 :
11+ return cls .__generate_vertical_text (text , font , text_color , font_size , space_width )
12+ else :
13+ raise Exception ("Unknown orientation " + str (orientation ))
14+
15+ @classmethod
16+ def __generate_horizontal_text (cls , text , font , text_color , font_size , space_width ):
817 image_font = ImageFont .truetype (font = font , size = font_size )
918 words = text .split (' ' )
1019 space_width = image_font .getsize (' ' )[0 ] * space_width
@@ -30,3 +39,31 @@ def generate(cls, text, font, text_color, font_size, orientation, space_width):
3039 txt_draw .text ((sum (words_width [0 :i ]) + i * int (space_width ), 0 ), w , fill = fill , font = image_font )
3140
3241 return txt_img
42+
43+ @classmethod
44+ def __generate_vertical_text (cls , text , font , text_color , font_size , space_width ):
45+ image_font = ImageFont .truetype (font = font , size = font_size )
46+
47+ space_height = int (image_font .getsize (' ' )[1 ] * space_width )
48+
49+ char_heights = [image_font .getsize (c )[1 ] if c != ' ' else space_height for c in text ]
50+ text_width = max ([image_font .getsize (c )[0 ] for c in text ])
51+ text_height = sum (char_heights )
52+
53+ txt_img = Image .new ('RGBA' , (text_width , text_height ), (0 , 0 , 0 , 0 ))
54+
55+ txt_draw = ImageDraw .Draw (txt_img )
56+
57+ colors = [ImageColor .getrgb (c ) for c in text_color .split (',' )]
58+ c1 , c2 = colors [0 ], colors [- 1 ]
59+
60+ fill = (
61+ random .randint (c1 [0 ], c2 [0 ]),
62+ random .randint (c1 [1 ], c2 [1 ]),
63+ random .randint (c1 [2 ], c2 [2 ])
64+ )
65+
66+ for i , c in enumerate (text ):
67+ txt_draw .text ((0 , sum (char_heights [0 :i ])), c , fill = fill , font = image_font )
68+
69+ return txt_img
0 commit comments