Advertisement
Guest User

Untitled

a guest
Jul 30th, 2021
282
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.52 KB | None | 0 0
  1. def text_image(text_path, font_path=None):
  2.  
  3.     grayscale = 'L'
  4.  
  5.     with open(text_path) as text_file:
  6.         lines = tuple(l.rstrip() for l in text_file.readlines())
  7.  
  8.     large_font = 15
  9.     font_path = font_path or 'font.ttf'
  10.     try:
  11.         font = PIL.ImageFont.truetype(font_path, size=large_font)
  12.     except IOError:
  13.         font = PIL.ImageFont.load_default()
  14.         print('Could not use chosen font. Using default.')
  15.  
  16.     pt2px = lambda pt: int(round(pt * 96.0 / 72))
  17.     max_width_line = max(lines, key=lambda s: font.getsize(s)[0])
  18.  
  19.     test_string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
  20.     max_height = pt2px(font.getsize(test_string)[1])
  21.     max_width = pt2px(font.getsize(max_width_line)[0])
  22.     mw = font.getsize(max_width_line)[0]
  23.     height = max_height * len(lines)
  24.     width = int(round(max_width + 40))
  25.    
  26.     block = int(max_width/max_height)
  27.     squareBlock = int(math.sqrt(len(lines)/block)) + 1
  28.    
  29.     image = PIL.Image.new(grayscale, (block * squareBlock* max_height, block * squareBlock* max_height), color=PIXEL_OFF)
  30.     draw = PIL.ImageDraw.Draw(image)
  31.        
  32.    
  33.     vertical_position = 20
  34.     horizontal_position = 20
  35.     line_spacing = int(round(max_height * 0.8))
  36.     i = 0
  37.     for e, line in enumerate(lines):
  38.         draw.text((horizontal_position, vertical_position),
  39.                   line, fill=PIXEL_ON, font=font)
  40.         vertical_position += line_spacing
  41.        
  42.         if e % block == 0 and not e==0:
  43.             i+=1
  44.         if i == squareBlock:
  45.             i = 0
  46.             horizontal_position += mw - 20
  47.             vertical_position = 20
  48.  
  49.     a, b, c, d = PIL.ImageOps.invert(image).getbbox()
  50.     image = image.crop((0,0,c+20,d+20))
  51.    
  52.     return image
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement