Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def text_image(text_path, font_path=None):
- grayscale = 'L'
- with open(text_path) as text_file:
- lines = tuple(l.rstrip() for l in text_file.readlines())
- large_font = 15
- font_path = font_path or 'font.ttf'
- try:
- font = PIL.ImageFont.truetype(font_path, size=large_font)
- except IOError:
- font = PIL.ImageFont.load_default()
- print('Could not use chosen font. Using default.')
- pt2px = lambda pt: int(round(pt * 96.0 / 72))
- max_width_line = max(lines, key=lambda s: font.getsize(s)[0])
- test_string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
- max_height = pt2px(font.getsize(test_string)[1])
- max_width = pt2px(font.getsize(max_width_line)[0])
- mw = font.getsize(max_width_line)[0]
- height = max_height * len(lines)
- width = int(round(max_width + 40))
- block = int(max_width/max_height)
- squareBlock = int(math.sqrt(len(lines)/block)) + 1
- image = PIL.Image.new(grayscale, (block * squareBlock* max_height, block * squareBlock* max_height), color=PIXEL_OFF)
- draw = PIL.ImageDraw.Draw(image)
- vertical_position = 20
- horizontal_position = 20
- line_spacing = int(round(max_height * 0.8))
- i = 0
- for e, line in enumerate(lines):
- draw.text((horizontal_position, vertical_position),
- line, fill=PIXEL_ON, font=font)
- vertical_position += line_spacing
- if e % block == 0 and not e==0:
- i+=1
- if i == squareBlock:
- i = 0
- horizontal_position += mw - 20
- vertical_position = 20
- a, b, c, d = PIL.ImageOps.invert(image).getbbox()
- image = image.crop((0,0,c+20,d+20))
- return image
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement