qrcodegen-demo.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. #
  2. # QR Code generator demo (Python)
  3. #
  4. # Run this command-line program with no arguments. The program computes a bunch of demonstration
  5. # QR Codes and prints them to the console. Also, the SVG code for one QR Code is printed as a sample.
  6. #
  7. # Copyright (c) Project Nayuki. (MIT License)
  8. # https://www.nayuki.io/page/qr-code-generator-library
  9. #
  10. # Permission is hereby granted, free of charge, to any person obtaining a copy of
  11. # this software and associated documentation files (the "Software"), to deal in
  12. # the Software without restriction, including without limitation the rights to
  13. # use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
  14. # the Software, and to permit persons to whom the Software is furnished to do so,
  15. # subject to the following conditions:
  16. # - The above copyright notice and this permission notice shall be included in
  17. # all copies or substantial portions of the Software.
  18. # - The Software is provided "as is", without warranty of any kind, express or
  19. # implied, including but not limited to the warranties of merchantability,
  20. # fitness for a particular purpose and noninfringement. In no event shall the
  21. # authors or copyright holders be liable for any claim, damages or other
  22. # liability, whether in an action of contract, tort or otherwise, arising from,
  23. # out of or in connection with the Software or the use or other dealings in the
  24. # Software.
  25. #
  26. from typing import List
  27. from qrcodegen import QrCode, QrSegment
  28. def main() -> None:
  29. """The main application program."""
  30. do_basic_demo()
  31. do_variety_demo()
  32. do_segment_demo()
  33. do_mask_demo()
  34. # ---- Demo suite ----
  35. def do_basic_demo() -> None:
  36. """Creates a single QR Code, then prints it to the console."""
  37. text = "Hello, world!" # User-supplied Unicode text
  38. errcorlvl = QrCode.Ecc.LOW # Error correction level
  39. # Make and print the QR Code symbol
  40. qr = QrCode.encode_text(text, errcorlvl)
  41. print_qr(qr)
  42. print(to_svg_str(qr, 4))
  43. def do_variety_demo() -> None:
  44. """Creates a variety of QR Codes that exercise different features of the library, and prints each one to the console."""
  45. # Numeric mode encoding (3.33 bits per digit)
  46. qr = QrCode.encode_text("314159265358979323846264338327950288419716939937510", QrCode.Ecc.MEDIUM)
  47. print_qr(qr)
  48. # Alphanumeric mode encoding (5.5 bits per character)
  49. qr = QrCode.encode_text("DOLLAR-AMOUNT:$39.87 PERCENTAGE:100.00% OPERATIONS:+-*/", QrCode.Ecc.HIGH)
  50. print_qr(qr)
  51. # Unicode text as UTF-8
  52. qr = QrCode.encode_text("\u3053\u3093\u306B\u3061\u0077\u0061\u3001\u4E16\u754C\uFF01\u0020\u03B1\u03B2\u03B3\u03B4", QrCode.Ecc.QUARTILE)
  53. print_qr(qr)
  54. # Moderately large QR Code using longer text (from Lewis Carroll's Alice in Wonderland)
  55. qr = QrCode.encode_text(
  56. "Alice was beginning to get very tired of sitting by her sister on the bank, "
  57. "and of having nothing to do: once or twice she had peeped into the book her sister was reading, "
  58. "but it had no pictures or conversations in it, 'and what is the use of a book,' thought Alice "
  59. "'without pictures or conversations?' So she was considering in her own mind (as well as she could, "
  60. "for the hot day made her feel very sleepy and stupid), whether the pleasure of making a "
  61. "daisy-chain would be worth the trouble of getting up and picking the daisies, when suddenly "
  62. "a White Rabbit with pink eyes ran close by her.", QrCode.Ecc.HIGH)
  63. print_qr(qr)
  64. def do_segment_demo() -> None:
  65. """Creates QR Codes with manually specified segments for better compactness."""
  66. # Illustration "silver"
  67. silver0 = "THE SQUARE ROOT OF 2 IS 1."
  68. silver1 = "41421356237309504880168872420969807856967187537694807317667973799"
  69. qr = QrCode.encode_text(silver0 + silver1, QrCode.Ecc.LOW)
  70. print_qr(qr)
  71. segs = [
  72. QrSegment.make_alphanumeric(silver0),
  73. QrSegment.make_numeric(silver1)]
  74. qr = QrCode.encode_segments(segs, QrCode.Ecc.LOW)
  75. print_qr(qr)
  76. # Illustration "golden"
  77. golden0 = "Golden ratio \u03C6 = 1."
  78. golden1 = "6180339887498948482045868343656381177203091798057628621354486227052604628189024497072072041893911374"
  79. golden2 = "......"
  80. qr = QrCode.encode_text(golden0 + golden1 + golden2, QrCode.Ecc.LOW)
  81. print_qr(qr)
  82. segs = [
  83. QrSegment.make_bytes(golden0.encode("UTF-8")),
  84. QrSegment.make_numeric(golden1),
  85. QrSegment.make_alphanumeric(golden2)]
  86. qr = QrCode.encode_segments(segs, QrCode.Ecc.LOW)
  87. print_qr(qr)
  88. # Illustration "Madoka": kanji, kana, Cyrillic, full-width Latin, Greek characters
  89. madoka = "\u300C\u9B54\u6CD5\u5C11\u5973\u307E\u3069\u304B\u2606\u30DE\u30AE\u30AB\u300D\u3063\u3066\u3001\u3000\u0418\u0410\u0418\u3000\uFF44\uFF45\uFF53\uFF55\u3000\u03BA\u03B1\uFF1F"
  90. qr = QrCode.encode_text(madoka, QrCode.Ecc.LOW)
  91. print_qr(qr)
  92. kanjicharbits = [ # Kanji mode encoding (13 bits per character)
  93. 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1,
  94. 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0,
  95. 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,
  96. 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1,
  97. 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 1,
  98. 0, 0, 0, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0,
  99. 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 1,
  100. 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1,
  101. 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 1,
  102. 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1,
  103. 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1,
  104. 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 0,
  105. 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0,
  106. 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1,
  107. 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0,
  108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
  109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  110. 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1,
  111. 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0,
  112. 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1,
  113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  114. 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0,
  115. 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1,
  116. 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1,
  117. 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1,
  118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119. 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0,
  120. 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0,
  122. ]
  123. segs = [QrSegment(QrSegment.Mode.KANJI, len(kanjicharbits) // 13, kanjicharbits)]
  124. qr = QrCode.encode_segments(segs, QrCode.Ecc.LOW)
  125. print_qr(qr)
  126. def do_mask_demo() -> None:
  127. """Creates QR Codes with the same size and contents but different mask patterns."""
  128. # Project Nayuki URL
  129. segs = QrSegment.make_segments("https://www.nayuki.io/")
  130. print_qr(QrCode.encode_segments(segs, QrCode.Ecc.HIGH, mask=-1)) # Automatic mask
  131. print_qr(QrCode.encode_segments(segs, QrCode.Ecc.HIGH, mask=3)) # Force mask 3
  132. # Chinese text as UTF-8
  133. segs = QrSegment.make_segments(
  134. "\u7DAD\u57FA\u767E\u79D1\uFF08\u0057\u0069\u006B\u0069\u0070\u0065\u0064\u0069\u0061\uFF0C"
  135. "\u8046\u807D\u0069\u002F\u02CC\u0077\u026A\u006B\u1D7B\u02C8\u0070\u0069\u02D0\u0064\u0069"
  136. "\u002E\u0259\u002F\uFF09\u662F\u4E00\u500B\u81EA\u7531\u5167\u5BB9\u3001\u516C\u958B\u7DE8"
  137. "\u8F2F\u4E14\u591A\u8A9E\u8A00\u7684\u7DB2\u8DEF\u767E\u79D1\u5168\u66F8\u5354\u4F5C\u8A08"
  138. "\u756B")
  139. print_qr(QrCode.encode_segments(segs, QrCode.Ecc.MEDIUM, mask=0)) # Force mask 0
  140. print_qr(QrCode.encode_segments(segs, QrCode.Ecc.MEDIUM, mask=1)) # Force mask 1
  141. print_qr(QrCode.encode_segments(segs, QrCode.Ecc.MEDIUM, mask=5)) # Force mask 5
  142. print_qr(QrCode.encode_segments(segs, QrCode.Ecc.MEDIUM, mask=7)) # Force mask 7
  143. # ---- Utilities ----
  144. def to_svg_str(qr: QrCode, border: int) -> str:
  145. """Returns a string of SVG code for an image depicting the given QR Code, with the given number
  146. of border modules. The string always uses Unix newlines (\n), regardless of the platform."""
  147. if border < 0:
  148. raise ValueError("Border must be non-negative")
  149. parts: List[str] = []
  150. for y in range(qr.get_size()):
  151. for x in range(qr.get_size()):
  152. if qr.get_module(x, y):
  153. parts.append(f"M{x+border},{y+border}h1v1h-1z")
  154. return f"""<?xml version="1.0" encoding="UTF-8"?>
  155. <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
  156. <svg xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 {qr.get_size()+border*2} {qr.get_size()+border*2}" stroke="none">
  157. <rect width="100%" height="100%" fill="#FFFFFF"/>
  158. <path d="{" ".join(parts)}" fill="#000000"/>
  159. </svg>
  160. """
  161. def print_qr(qrcode: QrCode) -> None:
  162. """Prints the given QrCode object to the console."""
  163. border = 4
  164. for y in range(-border, qrcode.get_size() + border):
  165. for x in range(-border, qrcode.get_size() + border):
  166. print("\u2588 "[1 if qrcode.get_module(x,y) else 0] * 2, end="")
  167. print()
  168. print()
  169. # Run the main program
  170. if __name__ == "__main__":
  171. main()