-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtextify.py
83 lines (63 loc) · 1.84 KB
/
textify.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
"""
Author : Sumanth Prabhu <[email protected]>
"""
from PIL import Image, ImageFont, ImageDraw
import random
import textwrap
import sys
#check for valid input
def validity(argv):
if len(argv) != 3:
return (False, "Missing arguments")
try:
with open(argv[1]) as f:
#check if it's an image file
if not argv[1].endswith(('.png', '.jpg', '.jpeg')):
return (False, "Please enter'png', 'jpg' or'jpeg' files only")
except IOError as e:
return (False, str(e))
else:
return (True, )
#textify the image
def textify(input_file, text_file):
#Open the input image
input_img = Image.open(input_file)
text_img = Image.new(input_img.mode, input_img.size, "white")
draw = ImageDraw.Draw(text_img)
#Generate image containing text
width = text_img.size[0]
height = text_img.size[1]
with open(text_file, 'r') as f:
input_txt = f.read()
text = input_txt * (width * height / len(input_txt))
lines = textwrap.wrap(text, width=width)
fontsize = 9
#windows
if sys.platform.startswith('win'):
font = ImageFont.truetype("ARIALN.TTF", fontsize)
#mac
elif sys.platform.startswith('darwin'):
font = ImageFont.truetype("~/Library/Fonts/Arial.ttf", fontsize)
#linux
else:
font = ImageFont.truetype("/usr/share/fonts/truetype/freefont/FreeMono.ttf", fontsize)
for h, line in enumerate(lines):
draw.text((0, h * fontsize), line, font=font, fill="black")
#Create output image
output_img = input_img.copy()
for i, px in enumerate(text_img.getdata()):
if px == (255, 255, 255) :
y = i / width
x = i % width
output_img.putpixel((x, y), (255, 255, 255))
output_img.save("output.jpg")
#Display output image
output_img.show()
def main():
resp = validity(sys.argv)
if resp[0]: #valid input
textify(sys.argv[1], sys.argv[2])
else:
print "Error : " + resp[1]
if __name__ == "__main__":
main()