forked from netbox-community/netbox-qrcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutilities.py
104 lines (84 loc) · 2.82 KB
/
utilities.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
import base64
import qrcode
from io import BytesIO
from PIL import Image, ImageFont, ImageDraw
from pkg_resources import resource_stream
def get_qr_with_text(qr, descr):
dsi = get_qr_text(qr.size, descr)
resimg = get_concat(qr, dsi)
return get_img_b64(resimg)
def get_qr(text, **kwargs):
qr = qrcode.QRCode(**kwargs)
qr.add_data(text)
qr.make(fit=True)
img = qr.make_image()
img = img.get_image()
return img
def get_img_b64(img):
stream = BytesIO()
img.save(stream, format='png')
return str(base64.b64encode(stream.getvalue()), encoding='ascii')
def get_qr_text(max_size, text, font='TahomaBold'):
font_size = 56
tmpimg = Image.new('L', max_size, 'white')
text_too_large = True
while text_too_large:
file_path = resource_stream(__name__, 'fonts/{}.ttf'.format(font))
try:
fnt = ImageFont.truetype(file_path, font_size)
except Exception:
fnt = ImageFont.load_default()
draw = ImageDraw.Draw(tmpimg)
w, h = draw.textsize(text, font=fnt)
if w < max_size[0] - 4 and h < max_size[1] - 4:
text_too_large = False
font_size -= 1
img = Image.new('L', (w, h), 'white')
draw = ImageDraw.Draw(img)
draw.text((0, 0), text, font=fnt, fill='black')
return img
def get_concat(im1, im2, direction='right'):
if direction == 'right' or direction == 'left':
width = im1.width + im2.width
height = max(im1.height, im2.height)
elif direction == 'down' or direction == 'up':
width = max(im1.width, im2.width)
height = im1.height + im2.height
else:
raise ValueError(
'Invalid direction "{}" (must be one of "left", "right", "up", or "down")'.format(direction)
)
dst = Image.new('L', (width, height), 'white')
if direction == 'right' or direction == 'left':
if im1.height > im2.height:
im1_y = 0
im2_y = abs(im1.height-im2.height) // 2
else:
im1_y = abs(im1.height-im2.height) // 2
im2_y = 0
if direction == 'right':
im1_x = 0
im2_x = im1.width
else:
im1_x = im2.width
im2_x = 0
elif direction == 'up' or direction == 'down':
if im1.width > im2.width:
im1_x = 0
im2_x = abs(im1.width-im2.width) // 2
else:
im1_x = abs(im1.width-im2.width) // 2
im2_x = 0
if direction == 'down':
im1_y = 0
im2_y = im1.height
else:
im1_y = im2.height
im2_y = 0
else:
raise ValueError(
'Invalid direction "{}" (must be one of "left", "right", "up", or "down")'.format(direction)
)
dst.paste(im1, (im1_x, im1_y))
dst.paste(im2, (im2_x, im2_y))
return dst