2015-03-07 19:41:19 +00:00
|
|
|
#!/usr/bin/python3
|
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
# vi:si:et:sw=4:sts=4:ts=4
|
|
|
|
from __future__ import division
|
|
|
|
import os
|
|
|
|
|
|
|
|
from PIL import Image
|
2017-01-25 22:39:43 +00:00
|
|
|
from argparse import ArgumentParser
|
2015-03-07 19:41:19 +00:00
|
|
|
from ox.image import drawText, wrapText
|
|
|
|
|
|
|
|
root_dir = os.path.normpath(os.path.abspath(os.path.dirname(__file__)))
|
|
|
|
os.chdir(root_dir)
|
|
|
|
|
|
|
|
|
2015-03-07 20:08:35 +00:00
|
|
|
def decode_line(line):
|
|
|
|
try:
|
|
|
|
line = line.decode('utf-8')
|
|
|
|
except:
|
|
|
|
try:
|
|
|
|
line = line.decode('latin-1')
|
|
|
|
except:
|
|
|
|
line = line.decode('utf-8', errors='replace')
|
|
|
|
return line
|
|
|
|
|
2015-03-07 19:41:19 +00:00
|
|
|
def render(infile, outfile):
|
|
|
|
|
2015-03-07 20:08:35 +00:00
|
|
|
with open(infile, 'rb') as f:
|
2015-03-07 19:41:19 +00:00
|
|
|
|
|
|
|
image_size = (768, 1024)
|
|
|
|
margin = 64
|
|
|
|
offset = margin
|
|
|
|
font_file = 'txt.ttf'
|
|
|
|
font_size = 24
|
|
|
|
line_height = 32
|
|
|
|
max_lines = (image_size[1] - 2 * margin) / line_height
|
|
|
|
|
|
|
|
image = Image.new('L', image_size, (255))
|
|
|
|
|
|
|
|
for line in f:
|
2015-03-07 20:08:35 +00:00
|
|
|
line = decode_line(line)
|
2015-03-07 19:41:19 +00:00
|
|
|
|
|
|
|
for line_ in line.strip().split('\r'):
|
|
|
|
|
|
|
|
lines = wrapText(
|
|
|
|
line_,
|
|
|
|
image_size[0] - 2 * margin,
|
|
|
|
# we don't want the last line that ends with an ellipsis
|
|
|
|
max_lines + 1,
|
|
|
|
'txt.ttf',
|
|
|
|
font_size
|
|
|
|
)
|
|
|
|
|
|
|
|
for line__ in lines:
|
|
|
|
drawText(
|
|
|
|
image,
|
|
|
|
(margin, offset),
|
|
|
|
line__,
|
|
|
|
font_file,
|
|
|
|
font_size,
|
|
|
|
(0)
|
|
|
|
)
|
|
|
|
offset += line_height
|
|
|
|
max_lines -= 1
|
|
|
|
|
|
|
|
if max_lines == 0:
|
|
|
|
break
|
|
|
|
|
|
|
|
if max_lines == 0:
|
|
|
|
break
|
|
|
|
|
|
|
|
if max_lines == 0:
|
|
|
|
break
|
|
|
|
|
2019-01-16 06:41:55 +00:00
|
|
|
image.save(outfile, quality=50)
|
2015-03-07 19:41:19 +00:00
|
|
|
|
|
|
|
|
|
|
|
def main():
|
2017-01-25 22:39:43 +00:00
|
|
|
parser = ArgumentParser()
|
|
|
|
parser.add_argument(
|
|
|
|
'-i', '--infile', dest='infile', help='txt file to be read', required=True
|
2015-03-07 19:41:19 +00:00
|
|
|
)
|
2017-01-25 22:39:43 +00:00
|
|
|
parser.add_argument(
|
|
|
|
'-o', '--outfile', dest='outfile', help='jpg file to be written', required=True
|
2015-03-07 19:41:19 +00:00
|
|
|
)
|
2017-01-25 22:39:43 +00:00
|
|
|
options = parser.parse_args()
|
|
|
|
render(options.infile, options.outfile)
|
2015-03-07 19:41:19 +00:00
|
|
|
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
|
|
|
main()
|
|
|
|
|