1import qrcode
2from PIL import Image, ImageDraw
3
4def create_qr_code(data, box_size, border):
5 qr = qrcode.QRCode(
6 version=1,
7 error_correction=qrcode.constants.ERROR_CORRECT_H, # 30% error correction
8 box_size=box_size,
9 border=border,
10 )
11 qr.add_data(data)
12 qr.make()
13 img = qr.make_image(fill_color='black', back_color='white').convert('RGBA')
14 img.save("!qrcode.png")
15 return img
16
17def create_mask(img, squares):
18 mask = Image.new('1', img.size, 0) # '1' for black and white
19 draw = ImageDraw.Draw(mask)
20 for square in squares:
21 draw.rectangle(square, fill=1) # fill the defined areas with white
22 mask_img = Image.new('RGBA', img.size, (0, 0, 0, 0)) # create with full transparency
23 mask_img.paste(img, mask=mask)
24 mask_img.save('!qrcode-mask.png')
25
26def main():
27 # Data you want to encode
28 data = "trimad.github.io/post/2023-06-24-qr"
29
30 # Define global variables
31 box_size = 32
32 border = 2
33 padding = border*box_size
34
35 img = create_qr_code(data, box_size, border)
36
37 # Define the size of squares
38 position_pattern = 8*box_size+((border-1)*box_size)``
39
40 # Define coordinates for 8x8 squares at the corners and an additional 5x5 square
41 squares = [
42 (padding, padding, position_pattern-1, position_pattern-1),
43 (img.size[0] - position_pattern, padding, img.size[0] - padding-1, position_pattern-1),
44 (padding, img.size[1] - position_pattern, position_pattern-1, img.size[1] - padding-1),
45 (28*box_size+padding, 28*box_size+padding, (28+5)*box_size+padding-1, (28+5)*box_size+padding-1)
46 ]
47
48 create_mask(img, squares)
49
50if __name__ == "__main__":
51 main()