builder.py 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528
  1. # -*- coding: utf-8 -*-
  2. # Copyright (c) 2013, Michael Nooner
  3. # All rights reserved.
  4. #
  5. # Redistribution and use in source and binary forms, with or without
  6. # modification, are permitted provided that the following conditions are met:
  7. # * Redistributions of source code must retain the above copyright
  8. # notice, this list of conditions and the following disclaimer.
  9. # * Redistributions in binary form must reproduce the above copyright
  10. # notice, this list of conditions and the following disclaimer in the
  11. # documentation and/or other materials provided with the distribution.
  12. # * Neither the name of the copyright holder nor the names of its
  13. # contributors may be used to endorse or promote products derived from
  14. # this software without specific prior written permission
  15. #
  16. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  17. # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  18. # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  19. # ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
  20. # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. """This module does the actual generation of the QR codes. The QRCodeBuilder
  27. builds the code. While the various output methods draw the code into a file.
  28. """
  29. #Imports required for 2.x support
  30. from __future__ import absolute_import, division, print_function, with_statement, unicode_literals
  31. import pyqrcode.tables as tables
  32. import io
  33. import itertools
  34. import math
  35. class QRCodeBuilder:
  36. """This class generates a QR code based on the standard. It is meant to
  37. be used internally, not by users!!!
  38. This class implements the tutorials found at:
  39. * http://www.thonky.com/qr-code-tutorial/
  40. * http://www.matchadesign.com/blog/qr-code-demystified-part-6/
  41. This class also uses the standard, which can be read online at:
  42. http://raidenii.net/files/datasheets/misc/qr_code.pdf
  43. Test codes were tested against:
  44. http://zxing.org/w/decode.jspx
  45. Also, reference codes were generat/ed at:
  46. http://www.morovia.com/free-online-barcode-generator/qrcode-maker.php
  47. http://demos.telerik.com/aspnet-ajax/barcode/examples/qrcode/defaultcs.aspx
  48. QR code Debugger:
  49. http://qrlogo.kaarposoft.dk/qrdecode.html
  50. """
  51. def __init__(self, data, version, mode, error):
  52. """See :py:class:`pyqrcode.QRCode` for information on the parameters."""
  53. #Set what data we are going to use to generate
  54. #the QR code
  55. self.data = data
  56. #Check that the user passed in a valid mode
  57. if mode in tables.modes:
  58. self.mode = tables.modes[mode]
  59. else:
  60. raise ValueError('{0} is not a valid mode.'.format(mode))
  61. #Check that the user passed in a valid error level
  62. if error in tables.error_level:
  63. self.error = tables.error_level[error]
  64. else:
  65. raise ValueError('{0} is not a valid error '
  66. 'level.'.format(error))
  67. if 1 <= version <= 40:
  68. self.version = version
  69. else:
  70. raise ValueError("Illegal version {0}, version must be between "
  71. "1 and 40.".format(version))
  72. #Look up the proper row for error correction code words
  73. self.error_code_words = tables.eccwbi[version][self.error]
  74. #This property will hold the binary string as it is built
  75. self.buffer = io.StringIO()
  76. #Create the binary data block
  77. self.add_data()
  78. #Create the actual QR code
  79. self.make_code()
  80. def grouper(self, n, iterable, fillvalue=None):
  81. """This generator yields a set of tuples, where the
  82. iterable is broken into n sized chunks. If the
  83. iterable is not evenly sized then fillvalue will
  84. be appended to the last tuple to make up the difference.
  85. This function is copied from the standard docs on
  86. itertools.
  87. """
  88. args = [iter(iterable)] * n
  89. if hasattr(itertools, 'zip_longest'):
  90. return itertools.zip_longest(*args, fillvalue=fillvalue)
  91. return itertools.izip_longest(*args, fillvalue=fillvalue)
  92. def binary_string(self, data, length):
  93. """This method returns a string of length n that is the binary
  94. representation of the given data. This function is used to
  95. basically create bit fields of a given size.
  96. """
  97. return '{{0:0{0}b}}'.format(length).format(int(data))
  98. def get_data_length(self):
  99. """QR codes contain a "data length" field. This method creates this
  100. field. A binary string representing the appropriate length is
  101. returned.
  102. """
  103. #The "data length" field varies by the type of code and its mode.
  104. #discover how long the "data length" field should be.
  105. if 1 <= self.version <= 9:
  106. max_version = 9
  107. elif 10 <= self.version <= 26:
  108. max_version = 26
  109. elif 27 <= self.version <= 40:
  110. max_version = 40
  111. data_length = tables.data_length_field[max_version][self.mode]
  112. if self.mode != tables.modes['kanji']:
  113. length_string = self.binary_string(len(self.data), data_length)
  114. else:
  115. length_string = self.binary_string(len(self.data) / 2, data_length)
  116. if len(length_string) > data_length:
  117. raise ValueError('The supplied data will not fit '
  118. 'within this version of a QRCode.')
  119. return length_string
  120. def encode(self):
  121. """This method encodes the data into a binary string using
  122. the appropriate algorithm specified by the mode.
  123. """
  124. if self.mode == tables.modes['alphanumeric']:
  125. encoded = self.encode_alphanumeric()
  126. elif self.mode == tables.modes['numeric']:
  127. encoded = self.encode_numeric()
  128. elif self.mode == tables.modes['binary']:
  129. encoded = self.encode_bytes()
  130. elif self.mode == tables.modes['kanji']:
  131. encoded = self.encode_kanji()
  132. return encoded
  133. def encode_alphanumeric(self):
  134. """This method encodes the QR code's data if its mode is
  135. alphanumeric. It returns the data encoded as a binary string.
  136. """
  137. #Convert the string to upper case
  138. self.data = self.data.upper()
  139. #Change the data such that it uses a QR code ascii table
  140. ascii = []
  141. for char in self.data:
  142. if isinstance(char, int):
  143. ascii.append(tables.ascii_codes[chr(char)])
  144. else:
  145. ascii.append(tables.ascii_codes[char])
  146. #Now perform the algorithm that will make the ascii into bit fields
  147. with io.StringIO() as buf:
  148. for (a,b) in self.grouper(2, ascii):
  149. if b is not None:
  150. buf.write(self.binary_string((45*a)+b, 11))
  151. else:
  152. #This occurs when there is an odd number
  153. #of characters in the data
  154. buf.write(self.binary_string(a, 6))
  155. #Return the binary string
  156. return buf.getvalue()
  157. def encode_numeric(self):
  158. """This method encodes the QR code's data if its mode is
  159. numeric. It returns the data encoded as a binary string.
  160. """
  161. with io.StringIO() as buf:
  162. #Break the number into groups of three digits
  163. for triplet in self.grouper(3, self.data):
  164. number = ''
  165. for digit in triplet:
  166. if isinstance(digit, int):
  167. digit = chr(digit)
  168. #Only build the string if digit is not None
  169. if digit:
  170. number = ''.join([number, digit])
  171. else:
  172. break
  173. #If the number is one digits, make a 4 bit field
  174. if len(number) == 1:
  175. bin = self.binary_string(number, 4)
  176. #If the number is two digits, make a 7 bit field
  177. elif len(number) == 2:
  178. bin = self.binary_string(number, 7)
  179. #Three digit numbers use a 10 bit field
  180. else:
  181. bin = self.binary_string(number, 10)
  182. buf.write(bin)
  183. return buf.getvalue()
  184. def encode_bytes(self):
  185. """This method encodes the QR code's data if its mode is
  186. 8 bit mode. It returns the data encoded as a binary string.
  187. """
  188. with io.StringIO() as buf:
  189. for char in self.data:
  190. if not isinstance(char, int):
  191. buf.write('{{0:0{0}b}}'.format(8).format(ord(char)))
  192. else:
  193. buf.write('{{0:0{0}b}}'.format(8).format(char))
  194. return buf.getvalue()
  195. def encode_kanji(self):
  196. """This method encodes the QR code's data if its mode is
  197. kanji. It returns the data encoded as a binary string.
  198. """
  199. def two_bytes(data):
  200. """Output two byte character code as a single integer."""
  201. def next_byte(b):
  202. """Make sure that character code is an int. Python 2 and
  203. 3 compatibility.
  204. """
  205. if not isinstance(b, int):
  206. return ord(b)
  207. else:
  208. return b
  209. #Go through the data by looping to every other character
  210. for i in range(0, len(data), 2):
  211. yield (next_byte(data[i]) << 8) | next_byte(data[i+1])
  212. #Force the data into Kanji encoded bytes
  213. if isinstance(self.data, bytes):
  214. data = self.data.decode('shiftjis').encode('shiftjis')
  215. else:
  216. data = self.data.encode('shiftjis')
  217. #Now perform the algorithm that will make the kanji into 13 bit fields
  218. with io.StringIO() as buf:
  219. for asint in two_bytes(data):
  220. #Shift the two byte value as indicated by the standard
  221. if 0x8140 <= asint <= 0x9FFC:
  222. difference = asint - 0x8140
  223. elif 0xE040 <= asint <= 0xEBBF:
  224. difference = asint - 0xC140
  225. #Split the new value into most and least significant bytes
  226. msb = (difference >> 8)
  227. lsb = (difference & 0x00FF)
  228. #Calculate the actual 13 bit binary value
  229. buf.write('{0:013b}'.format((msb * 0xC0) + lsb))
  230. #Return the binary string
  231. return buf.getvalue()
  232. def add_data(self):
  233. """This function properly constructs a QR code's data string. It takes
  234. into account the interleaving pattern required by the standard.
  235. """
  236. #Encode the data into a QR code
  237. self.buffer.write(self.binary_string(self.mode, 4))
  238. self.buffer.write(self.get_data_length())
  239. self.buffer.write(self.encode())
  240. #Converts the buffer into "code word" integers.
  241. #The online debugger outputs them this way, makes
  242. #for easier comparisons.
  243. #s = self.buffer.getvalue()
  244. #for i in range(0, len(s), 8):
  245. # print(int(s[i:i+8], 2), end=',')
  246. #print()
  247. #Fix for issue #3: https://github.com/mnooner256/pyqrcode/issues/3#
  248. #I was performing the terminate_bits() part in the encoding.
  249. #As per the standard, terminating bits are only supposed to
  250. #be added after the bit stream is complete. I took that to
  251. #mean after the encoding, but actually it is after the entire
  252. #bit stream has been constructed.
  253. bits = self.terminate_bits(self.buffer.getvalue())
  254. if bits is not None:
  255. self.buffer.write(bits)
  256. #delimit_words and add_words can return None
  257. add_bits = self.delimit_words()
  258. if add_bits:
  259. self.buffer.write(add_bits)
  260. fill_bytes = self.add_words()
  261. if fill_bytes:
  262. self.buffer.write(fill_bytes)
  263. #Get a numeric representation of the data
  264. data = [int(''.join(x),2)
  265. for x in self.grouper(8, self.buffer.getvalue())]
  266. #This is the error information for the code
  267. error_info = tables.eccwbi[self.version][self.error]
  268. #This will hold our data blocks
  269. data_blocks = []
  270. #This will hold our error blocks
  271. error_blocks = []
  272. #Some codes have the data sliced into two different sized blocks
  273. #for example, first two 14 word sized blocks, then four 15 word
  274. #sized blocks. This means that slicing size can change over time.
  275. data_block_sizes = [error_info[2]] * error_info[1]
  276. if error_info[3] != 0:
  277. data_block_sizes.extend([error_info[4]] * error_info[3])
  278. #For every block of data, slice the data into the appropriate
  279. #sized block
  280. current_byte = 0
  281. for n_data_blocks in data_block_sizes:
  282. data_blocks.append(data[current_byte:current_byte+n_data_blocks])
  283. current_byte += n_data_blocks
  284. #I am not sure about the test after the "and". This was added to
  285. #fix a bug where after delimit_words padded the bit stream, a zero
  286. #byte ends up being added. After checking around, it seems this extra
  287. #byte is supposed to be chopped off, but I cannot find that in the
  288. #standard! I am adding it to solve the bug, I believe it is correct.
  289. if current_byte < len(data):
  290. raise ValueError('Too much data for this code version.')
  291. #DEBUG CODE!!!!
  292. #Print out the data blocks
  293. #print('Data Blocks:\n{0}'.format(data_blocks))
  294. #Calculate the error blocks
  295. for n, block in enumerate(data_blocks):
  296. error_blocks.append(self.make_error_block(block, n))
  297. #DEBUG CODE!!!!
  298. #Print out the error blocks
  299. #print('Error Blocks:\n{0}'.format(error_blocks))
  300. #Buffer we will write our data blocks into
  301. data_buffer = io.StringIO()
  302. #Add the data blocks
  303. #Write the buffer such that: block 1 byte 1, block 2 byte 1, etc.
  304. largest_block = max(error_info[2], error_info[4])+error_info[0]
  305. for i in range(largest_block):
  306. for block in data_blocks:
  307. if i < len(block):
  308. data_buffer.write(self.binary_string(block[i], 8))
  309. #Add the error code blocks.
  310. #Write the buffer such that: block 1 byte 1, block 2 byte 2, etc.
  311. for i in range(error_info[0]):
  312. for block in error_blocks:
  313. data_buffer.write(self.binary_string(block[i], 8))
  314. self.buffer = data_buffer
  315. def terminate_bits(self, payload):
  316. """This method adds zeros to the end of the encoded data so that the
  317. encoded data is of the correct length. It returns a binary string
  318. containing the bits to be added.
  319. """
  320. data_capacity = tables.data_capacity[self.version][self.error][0]
  321. if len(payload) > data_capacity:
  322. raise ValueError('The supplied data will not fit '
  323. 'within this version of a QR code.')
  324. #We must add up to 4 zeros to make up for any shortfall in the
  325. #length of the data field.
  326. if len(payload) == data_capacity:
  327. return None
  328. elif len(payload) <= data_capacity-4:
  329. bits = self.binary_string(0,4)
  330. else:
  331. #Make up any shortfall need with less than 4 zeros
  332. bits = self.binary_string(0, data_capacity - len(payload))
  333. return bits
  334. def delimit_words(self):
  335. """This method takes the existing encoded binary string
  336. and returns a binary string that will pad it such that
  337. the encoded string contains only full bytes.
  338. """
  339. bits_short = 8 - (len(self.buffer.getvalue()) % 8)
  340. #The string already falls on an byte boundary do nothing
  341. if bits_short == 0 or bits_short == 8:
  342. return None
  343. else:
  344. return self.binary_string(0, bits_short)
  345. def add_words(self):
  346. """The data block must fill the entire data capacity of the QR code.
  347. If we fall short, then we must add bytes to the end of the encoded
  348. data field. The value of these bytes are specified in the standard.
  349. """
  350. data_blocks = len(self.buffer.getvalue()) // 8
  351. total_blocks = tables.data_capacity[self.version][self.error][0] // 8
  352. needed_blocks = total_blocks - data_blocks
  353. if needed_blocks == 0:
  354. return None
  355. #This will return item1, item2, item1, item2, etc.
  356. block = itertools.cycle(['11101100', '00010001'])
  357. #Create a string of the needed blocks
  358. return ''.join([next(block) for x in range(needed_blocks)])
  359. def make_error_block(self, block, block_number):
  360. """This function constructs the error correction block of the
  361. given data block. This is *very complicated* process. To
  362. understand the code you need to read:
  363. * http://www.thonky.com/qr-code-tutorial/part-2-error-correction/
  364. * http://www.matchadesign.com/blog/qr-code-demystified-part-4/
  365. """
  366. #Get the error information from the standards table
  367. error_info = tables.eccwbi[self.version][self.error]
  368. #This is the number of 8-bit words per block
  369. if block_number < error_info[1]:
  370. code_words_per_block = error_info[2]
  371. else:
  372. code_words_per_block = error_info[4]
  373. #This is the size of the error block
  374. error_block_size = error_info[0]
  375. #Copy the block as the message polynomial coefficients
  376. mp_co = block[:]
  377. #Add the error blocks to the message polynomial
  378. mp_co.extend([0] * (error_block_size))
  379. #Get the generator polynomial
  380. generator = tables.generator_polynomials[error_block_size]
  381. #This will hold the temporary sum of the message coefficient and the
  382. #generator polynomial
  383. gen_result = [0] * len(generator)
  384. #Go through every code word in the block
  385. for i in range(code_words_per_block):
  386. #Get the first coefficient from the message polynomial
  387. coefficient = mp_co.pop(0)
  388. #Skip coefficients that are zero
  389. if coefficient == 0:
  390. continue
  391. else:
  392. #Turn the coefficient into an alpha exponent
  393. alpha_exp = tables.galois_antilog[coefficient]
  394. #Add the alpha to the generator polynomial
  395. for n in range(len(generator)):
  396. gen_result[n] = alpha_exp + generator[n]
  397. if gen_result[n] > 255:
  398. gen_result[n] = gen_result[n] % 255
  399. #Convert the alpha notation back into coefficients
  400. gen_result[n] = tables.galois_log[gen_result[n]]
  401. #XOR the sum with the message coefficients
  402. mp_co[n] = gen_result[n] ^ mp_co[n]
  403. #Pad the end of the error blocks with zeros if needed
  404. if len(mp_co) < code_words_per_block:
  405. mp_co.extend([0] * (code_words_per_block - len(mp_co)))
  406. return mp_co
  407. def make_code(self):
  408. """This method returns the best possible QR code."""
  409. from copy import deepcopy
  410. #Get the size of the underlying matrix
  411. matrix_size = tables.version_size[self.version]
  412. #Create a template matrix we will build the codes with
  413. row = [' ' for x in range(matrix_size)]
  414. template = [deepcopy(row) for x in range(matrix_size)]
  415. #Add mandatory information to the template
  416. self.add_detection_pattern(template)
  417. self.add_position_pattern(template)
  418. self.add_version_pattern(template)
  419. #Create the various types of masks of the template
  420. self.masks = self.make_masks(template)
  421. self.best_mask = self.choose_best_mask()
  422. self.code = self.masks[self.best_mask]
  423. def add_detection_pattern(self, m):
  424. """This method add the detection patterns to the QR code. This lets
  425. the scanner orient the pattern. It is required for all QR codes.
  426. The detection pattern consists of three boxes located at the upper
  427. left, upper right, and lower left corners of the matrix. Also, two
  428. special lines called the timing pattern is also necessary. Finally,
  429. a single black pixel is added just above the lower left black box.
  430. """
  431. #Draw outer black box
  432. for i in range(7):
  433. inv = -(i+1)
  434. for j in [0,6,-1,-7]:
  435. m[j][i] = 1
  436. m[i][j] = 1
  437. m[inv][j] = 1
  438. m[j][inv] = 1
  439. #Draw inner white box
  440. for i in range(1, 6):
  441. inv = -(i+1)
  442. for j in [1, 5, -2, -6]:
  443. m[j][i] = 0
  444. m[i][j] = 0
  445. m[inv][j] = 0
  446. m[j][inv] = 0
  447. #Draw inner black box
  448. for i in range(2, 5):
  449. for j in range(2, 5):
  450. inv = -(i+1)
  451. m[i][j] = 1
  452. m[inv][j] = 1
  453. m[j][inv] = 1
  454. #Draw white border
  455. for i in range(8):
  456. inv = -(i+1)
  457. for j in [7, -8]:
  458. m[i][j] = 0
  459. m[j][i] = 0
  460. m[inv][j] = 0
  461. m[j][inv] = 0
  462. #To keep the code short, it draws an extra box
  463. #in the lower right corner, this removes it.
  464. for i in range(-8, 0):
  465. for j in range(-8, 0):
  466. m[i][j] = ' '
  467. #Add the timing pattern
  468. bit = itertools.cycle([1,0])
  469. for i in range(8, (len(m)-8)):
  470. b = next(bit)
  471. m[i][6] = b
  472. m[6][i] = b
  473. #Add the extra black pixel
  474. m[-8][8] = 1
  475. def add_position_pattern(self, m):
  476. """This method draws the position adjustment patterns onto the QR
  477. Code. All QR code versions larger than one require these special boxes
  478. called position adjustment patterns.
  479. """
  480. #Version 1 does not have a position adjustment pattern
  481. if self.version == 1:
  482. return
  483. #Get the coordinates for where to place the boxes
  484. coordinates = tables.position_adjustment[self.version]
  485. #Get the max and min coordinates to handle special cases
  486. min_coord = coordinates[0]
  487. max_coord = coordinates[-1]
  488. #Draw a box at each intersection of the coordinates
  489. for i in coordinates:
  490. for j in coordinates:
  491. #Do not draw these boxes because they would
  492. #interfere with the detection pattern
  493. if (i == min_coord and j == min_coord) or \
  494. (i == min_coord and j == max_coord) or \
  495. (i == max_coord and j == min_coord):
  496. continue
  497. #Center black pixel
  498. m[i][j] = 1
  499. #Surround the pixel with a white box
  500. for x in [-1,1]:
  501. m[i+x][j+x] = 0
  502. m[i+x][j] = 0
  503. m[i][j+x] = 0
  504. m[i-x][j+x] = 0
  505. m[i+x][j-x] = 0
  506. #Surround the white box with a black box
  507. for x in [-2,2]:
  508. for y in [0,-1,1]:
  509. m[i+x][j+x] = 1
  510. m[i+x][j+y] = 1
  511. m[i+y][j+x] = 1
  512. m[i-x][j+x] = 1
  513. m[i+x][j-x] = 1
  514. def add_version_pattern(self, m):
  515. """For QR codes with a version 7 or higher, a special pattern
  516. specifying the code's version is required.
  517. For further information see:
  518. http://www.thonky.com/qr-code-tutorial/format-version-information/#example-of-version-7-information-string
  519. """
  520. if self.version < 7:
  521. return
  522. #Get the bit fields for this code's version
  523. #We will iterate across the string, the bit string
  524. #needs the least significant digit in the zero-th position
  525. field = iter(tables.version_pattern[self.version][::-1])
  526. #Where to start placing the pattern
  527. start = len(m)-11
  528. #The version pattern is pretty odd looking
  529. for i in range(6):
  530. #The pattern is three modules wide
  531. for j in range(start, start+3):
  532. bit = int(next(field))
  533. #Bottom Left
  534. m[i][j] = bit
  535. #Upper right
  536. m[j][i] = bit
  537. def make_masks(self, template):
  538. """This method generates all seven masks so that the best mask can
  539. be determined. The template parameter is a code matrix that will
  540. server as the base for all the generated masks.
  541. """
  542. from copy import deepcopy
  543. nmasks = len(tables.mask_patterns)
  544. masks = [''] * nmasks
  545. count = 0
  546. for n in range(nmasks):
  547. cur_mask = deepcopy(template)
  548. masks[n] = cur_mask
  549. #Add the type pattern bits to the code
  550. self.add_type_pattern(cur_mask, tables.type_bits[self.error][n])
  551. #Get the mask pattern
  552. pattern = tables.mask_patterns[n]
  553. #This will read the 1's and 0's one at a time
  554. bits = iter(self.buffer.getvalue())
  555. #These will help us do the up, down, up, down pattern
  556. row_start = itertools.cycle([len(cur_mask)-1, 0])
  557. row_stop = itertools.cycle([-1,len(cur_mask)])
  558. direction = itertools.cycle([-1, 1])
  559. #The data pattern is added using pairs of columns
  560. for column in range(len(cur_mask)-1, 0, -2):
  561. #The vertical timing pattern is an exception to the rules,
  562. #move the column counter over by one
  563. if column <= 6:
  564. column = column - 1
  565. #This will let us fill in the pattern
  566. #right-left, right-left, etc.
  567. column_pair = itertools.cycle([column, column-1])
  568. #Go through each row in the pattern moving up, then down
  569. for row in range(next(row_start), next(row_stop),
  570. next(direction)):
  571. #Fill in the right then left column
  572. for i in range(2):
  573. col = next(column_pair)
  574. #Go to the next column if we encounter a
  575. #preexisting pattern (usually an alignment pattern)
  576. if cur_mask[row][col] != ' ':
  577. continue
  578. #Some versions don't have enough bits. You then fill
  579. #in the rest of the pattern with 0's. These are
  580. #called "remainder bits."
  581. try:
  582. bit = int(next(bits))
  583. except:
  584. bit = 0
  585. #If the pattern is True then flip the bit
  586. if pattern(row, col):
  587. cur_mask[row][col] = bit ^ 1
  588. else:
  589. cur_mask[row][col] = bit
  590. #DEBUG CODE!!!
  591. #Save all of the masks as png files
  592. #for i, m in enumerate(masks):
  593. # _png(m, self.version, 'mask-{0}.png'.format(i), 5)
  594. return masks
  595. def choose_best_mask(self):
  596. """This method returns the index of the "best" mask as defined by
  597. having the lowest total penalty score. The penalty rules are defined
  598. by the standard. The mask with the lowest total score should be the
  599. easiest to read by optical scanners.
  600. """
  601. self.scores = []
  602. for n in range(len(self.masks)):
  603. self.scores.append([0,0,0,0])
  604. #Score penalty rule number 1
  605. #Look for five consecutive squares with the same color.
  606. #Each one found gets a penalty of 3 + 1 for every
  607. #same color square after the first five in the row.
  608. for (n, mask) in enumerate(self.masks):
  609. current = mask[0][0]
  610. counter = 0
  611. total = 0
  612. #Examine the mask row wise
  613. for row in range(0,len(mask)):
  614. counter = 0
  615. for col in range(0,len(mask)):
  616. bit = mask[row][col]
  617. if bit == current:
  618. counter += 1
  619. else:
  620. if counter >= 5:
  621. total += (counter - 5) + 3
  622. counter = 1
  623. current = bit
  624. if counter >= 5:
  625. total += (counter - 5) + 3
  626. #Examine the mask column wise
  627. for col in range(0,len(mask)):
  628. counter = 0
  629. for row in range(0,len(mask)):
  630. bit = mask[row][col]
  631. if bit == current:
  632. counter += 1
  633. else:
  634. if counter >= 5:
  635. total += (counter - 5) + 3
  636. counter = 1
  637. current = bit
  638. if counter >= 5:
  639. total += (counter - 5) + 3
  640. self.scores[n][0] = total
  641. #Score penalty rule 2
  642. #This rule will add 3 to the score for each 2x2 block of the same
  643. #colored pixels there are.
  644. for (n, mask) in enumerate(self.masks):
  645. count = 0
  646. #Don't examine the 0th and Nth row/column
  647. for i in range(0, len(mask)-1):
  648. for j in range(0, len(mask)-1):
  649. if mask[i][j] == mask[i+1][j] and \
  650. mask[i][j] == mask[i][j+1] and \
  651. mask[i][j] == mask[i+1][j+1]:
  652. count += 1
  653. self.scores[n][1] = count * 3
  654. #Score penalty rule 3
  655. #This rule looks for 1011101 within the mask prefixed
  656. #and/or suffixed by four zeros.
  657. patterns = [[0,0,0,0,1,0,1,1,1,0,1],
  658. [1,0,1,1,1,0,1,0,0,0,0],]
  659. #[0,0,0,0,1,0,1,1,1,0,1,0,0,0,0]]
  660. for (n, mask) in enumerate(self.masks):
  661. nmatches = 0
  662. for i in range(len(mask)):
  663. for j in range(len(mask)):
  664. for pattern in patterns:
  665. match = True
  666. k = j
  667. #Look for row matches
  668. for p in pattern:
  669. if k >= len(mask) or mask[i][k] != p:
  670. match = False
  671. break
  672. k += 1
  673. if match:
  674. nmatches += 1
  675. match = True
  676. k = j
  677. #Look for column matches
  678. for p in pattern:
  679. if k >= len(mask) or mask[k][i] != p:
  680. match = False
  681. break
  682. k += 1
  683. if match:
  684. nmatches += 1
  685. self.scores[n][2] = nmatches * 40
  686. #Score the last rule, penalty rule 4. This rule measures how close
  687. #the pattern is to being 50% black. The further it deviates from
  688. #this this ideal the higher the penalty.
  689. for (n, mask) in enumerate(self.masks):
  690. nblack = 0
  691. for row in mask:
  692. nblack += sum(row)
  693. total_pixels = len(mask)**2
  694. ratio = nblack / total_pixels
  695. percent = (ratio * 100) - 50
  696. self.scores[n][3] = int((abs(int(percent)) / 5) * 10)
  697. #Calculate the total for each score
  698. totals = [0] * len(self.scores)
  699. for i in range(len(self.scores)):
  700. for j in range(len(self.scores[i])):
  701. totals[i] += self.scores[i][j]
  702. #DEBUG CODE!!!
  703. #Prints out a table of scores
  704. #print('Rule Scores\n 1 2 3 4 Total')
  705. #for i in range(len(self.scores)):
  706. # print(i, end='')
  707. # for s in self.scores[i]:
  708. # print('{0: >6}'.format(s), end='')
  709. # print('{0: >7}'.format(totals[i]))
  710. #print('Mask Chosen: {0}'.format(totals.index(min(totals))))
  711. #The lowest total wins
  712. return totals.index(min(totals))
  713. def add_type_pattern(self, m, type_bits):
  714. """This will add the pattern to the QR code that represents the error
  715. level and the type of mask used to make the code.
  716. """
  717. field = iter(type_bits)
  718. for i in range(7):
  719. bit = int(next(field))
  720. #Skip the timing bits
  721. if i < 6:
  722. m[8][i] = bit
  723. else:
  724. m[8][i+1] = bit
  725. if -8 < -(i+1):
  726. m[-(i+1)][8] = bit
  727. for i in range(-8,0):
  728. bit = int(next(field))
  729. m[8][i] = bit
  730. i = -i
  731. #Skip timing column
  732. if i > 6:
  733. m[i][8] = bit
  734. else:
  735. m[i-1][8] = bit
  736. ##############################################################################
  737. ##############################################################################
  738. #
  739. # Output Functions
  740. #
  741. ##############################################################################
  742. ##############################################################################
  743. def _get_writable(stream_or_path, mode):
  744. """This method returns a tuple containing the stream and a flag to indicate
  745. if the stream should be automatically closed.
  746. The `stream_or_path` parameter is returned if it is an open writable stream.
  747. Otherwise, it treats the `stream_or_path` parameter as a file path and
  748. opens it with the given mode.
  749. It is used by the svg and png methods to interpret the file parameter.
  750. :type stream_or_path: str | io.BufferedIOBase
  751. :type mode: str | unicode
  752. :rtype: (io.BufferedIOBase, bool)
  753. """
  754. is_stream = hasattr(stream_or_path, 'write')
  755. if not is_stream:
  756. # No stream provided, treat "stream_or_path" as path
  757. stream_or_path = open(stream_or_path, mode)
  758. return stream_or_path, not is_stream
  759. def _get_png_size(version, scale, quiet_zone=4):
  760. """See: QRCode.get_png_size
  761. This function was abstracted away from QRCode to allow for the output of
  762. QR codes during the build process, i.e. for debugging. It works
  763. just the same except you must specify the code's version. This is needed
  764. to calculate the PNG's size.
  765. """
  766. #Formula: scale times number of modules plus the border on each side
  767. return (int(scale) * tables.version_size[version]) + (2 * quiet_zone * int(scale))
  768. def _terminal(code, module_color='default', background='reverse', quiet_zone=4):
  769. """This method returns a string containing ASCII escape codes,
  770. such that if printed to a terminal, it will display a vaild
  771. QR code. The module_color and the background color should be keys
  772. in the tables.term_colors table for printing using the 8/16
  773. color scheme. Alternatively, they can be a number between 0 and
  774. 256 in order to use the 88/256 color scheme. Otherwise, a
  775. ValueError will be raised.
  776. Note, the code is outputted by changing the background color. Then
  777. two spaces are written to the terminal. Finally, the terminal is
  778. reset back to how it was.
  779. """
  780. buf = io.StringIO()
  781. def draw_border():
  782. for i in range(quiet_zone):
  783. buf.write(background)
  784. if module_color in tables.term_colors:
  785. data = '\033[{0}m \033[0m'.format(
  786. tables.term_colors[module_color])
  787. elif 0 <= module_color <= 256:
  788. data = '\033[48;5;{0}m \033[0m'.format(module_color)
  789. else:
  790. raise ValueError('The module color, {0}, must a key in '
  791. 'pyqrcode.tables.term_colors or a number '
  792. 'between 0 and 256.'.format(
  793. module_color))
  794. if background in tables.term_colors:
  795. background = '\033[{0}m \033[0m'.format(
  796. tables.term_colors[background])
  797. elif 0 <= background <= 256:
  798. background = '\033[48;5;{0}m \033[0m'.format(background)
  799. else:
  800. raise ValueError('The background color, {0}, must a key in '
  801. 'pyqrcode.tables.term_colors or a number '
  802. 'between 0 and 256.'.format(
  803. background))
  804. #This will be the beginning and ending row for the code.
  805. border_row = background * (len(code[0]) + (2 * quiet_zone))
  806. #Make sure we begin on a new line, and force the terminal back
  807. #to normal
  808. buf.write('\n')
  809. #QRCodes have a quiet zone consisting of background modules
  810. for i in range(quiet_zone):
  811. buf.write(border_row)
  812. buf.write('\n')
  813. for row in code:
  814. #Each code has a quiet zone on the left side, this is the left
  815. #border for this code
  816. draw_border()
  817. for bit in row:
  818. if bit == 1:
  819. buf.write(data)
  820. elif bit == 0:
  821. buf.write(background)
  822. #Each row ends with a quiet zone on the right side, this is the
  823. #right hand border background modules
  824. draw_border()
  825. buf.write('\n')
  826. #QRCodes have a background quiet zone row following the code
  827. for i in range(quiet_zone):
  828. buf.write(border_row)
  829. buf.write('\n')
  830. return buf.getvalue()
  831. def _text(code, quiet_zone=4):
  832. """This method returns a text based representation of the QR code.
  833. This is useful for debugging purposes.
  834. """
  835. buf = io.StringIO()
  836. border_row = '0' * (len(code[0]) + (quiet_zone*2))
  837. #Every QR code start with a quiet zone at the top
  838. for b in range(quiet_zone):
  839. buf.write(border_row)
  840. buf.write('\n')
  841. for row in code:
  842. #Draw the starting quiet zone
  843. for b in range(quiet_zone):
  844. buf.write('0')
  845. #Actually draw the QR code
  846. for bit in row:
  847. if bit == 1:
  848. buf.write('1')
  849. elif bit == 0:
  850. buf.write('0')
  851. #This is for debugging unfinished QR codes,
  852. #unset pixels will be spaces.
  853. else:
  854. buf.write(' ')
  855. #Draw the ending quiet zone
  856. for b in range(quiet_zone):
  857. buf.write('0')
  858. buf.write('\n')
  859. #Every QR code ends with a quiet zone at the bottom
  860. for b in range(quiet_zone):
  861. buf.write(border_row)
  862. buf.write('\n')
  863. return buf.getvalue()
  864. def _xbm(code, scale=1, quiet_zone=4):
  865. """This function will format the QR code as a X BitMap.
  866. This can be used to display the QR code with Tkinter.
  867. """
  868. try:
  869. str = unicode # Python 2
  870. except NameError:
  871. str = __builtins__['str']
  872. buf = io.StringIO()
  873. # Calculate the width in pixels
  874. pixel_width = (len(code[0]) + quiet_zone * 2) * scale
  875. # Add the size information and open the pixel data section
  876. buf.write('#define im_width ')
  877. buf.write(str(pixel_width))
  878. buf.write('\n')
  879. buf.write('#define im_height ')
  880. buf.write(str(pixel_width))
  881. buf.write('\n')
  882. buf.write('static char im_bits[] = {\n')
  883. # Calculate the number of bytes per row
  884. byte_width = int(math.ceil(pixel_width / 8.0))
  885. # Add the top quiet zone
  886. buf.write(('0x00,' * byte_width + '\n') * quiet_zone * scale)
  887. for row in code:
  888. # Add the left quiet zone
  889. row_bits = '0' * quiet_zone * scale
  890. # Add the actual QR code
  891. for pixel in row:
  892. row_bits += str(pixel) * scale
  893. # Add the right quiet zone
  894. row_bits += '0' * quiet_zone * scale
  895. # Format the row
  896. formated_row = ''
  897. for b in range(byte_width):
  898. formated_row += '0x{0:02x},'.format(int(row_bits[:8][::-1], 2))
  899. row_bits = row_bits[8:]
  900. formated_row += '\n'
  901. # Add the formatted row
  902. buf.write(formated_row * scale)
  903. # Add the bottom quiet zone and close the pixel data section
  904. buf.write(('0x00,' * byte_width + '\n') * quiet_zone * scale)
  905. buf.write('};')
  906. return buf.getvalue()
  907. def _svg(code, version, file, scale=1, module_color='#000', background=None,
  908. quiet_zone=4, xmldecl=True, svgns=True, title=None, svgclass='pyqrcode',
  909. lineclass='pyqrline', omithw=False, debug=False):
  910. """This function writes the QR code out as an SVG document. The
  911. code is drawn by drawing only the modules corresponding to a 1. They
  912. are drawn using a line, such that contiguous modules in a row
  913. are drawn with a single line. The file parameter is used to
  914. specify where to write the document to. It can either be a writable (binary)
  915. stream or a file path. The scale parameter is sets how large to draw
  916. a single module. By default one pixel is used to draw a single
  917. module. This may make the code to small to be read efficiently.
  918. Increasing the scale will make the code larger. This method will accept
  919. fractional scales (e.g. 2.5).
  920. :param module_color: Color of the QR code (default: ``#000`` (black))
  921. :param background: Optional background color.
  922. (default: ``None`` (no background))
  923. :param quiet_zone: Border around the QR code (also known as quiet zone)
  924. (default: ``4``). Set to zero (``0``) if the code shouldn't
  925. have a border.
  926. :param xmldecl: Inidcates if the XML declaration header should be written
  927. (default: ``True``)
  928. :param svgns: Indicates if the SVG namespace should be written
  929. (default: ``True``)
  930. :param title: Optional title of the generated SVG document.
  931. :param svgclass: The CSS class of the SVG document
  932. (if set to ``None``, the SVG element won't have a class).
  933. :param lineclass: The CSS class of the path element
  934. (if set to ``None``, the path won't have a class).
  935. :param omithw: Indicates if width and height attributes should be
  936. omitted (default: ``False``). If these attributes are omitted,
  937. a ``viewBox`` attribute will be added to the document.
  938. :param debug: Inidicates if errors in the QR code should be added to the
  939. output (default: ``False``).
  940. """
  941. from functools import partial
  942. from xml.sax.saxutils import quoteattr
  943. def write_unicode(write_meth, unicode_str):
  944. """\
  945. Encodes the provided string into UTF-8 and writes the result using
  946. the `write_meth`.
  947. """
  948. write_meth(unicode_str.encode('utf-8'))
  949. def line(x, y, length, relative):
  950. """Returns coordinates to draw a line with the provided length.
  951. """
  952. return '{0}{1} {2}h{3}'.format(('m' if relative else 'M'), x, y, length)
  953. def errline(col_number, row_number):
  954. """Returns the coordinates to draw an error bit.
  955. """
  956. # Debug path uses always absolute coordinates
  957. # .5 == stroke / 2
  958. return line(col_number + quiet_zone, row_number + quiet_zone + .5, 1, False)
  959. f, autoclose = _get_writable(file, 'wb')
  960. write = partial(write_unicode, f.write)
  961. write_bytes = f.write
  962. # Write the document header
  963. if xmldecl:
  964. write_bytes(b'<?xml version="1.0" encoding="UTF-8"?>\n')
  965. write_bytes(b'<svg')
  966. if svgns:
  967. write_bytes(b' xmlns="http://www.w3.org/2000/svg"')
  968. size = tables.version_size[version] * scale + (2 * quiet_zone * scale)
  969. if not omithw:
  970. write(' height="{0}" width="{0}"'.format(size))
  971. else:
  972. write(' viewBox="0 0 {0} {0}"'.format(size))
  973. if svgclass is not None:
  974. write_bytes(b' class=')
  975. write(quoteattr(svgclass))
  976. write_bytes(b'>')
  977. if title is not None:
  978. write('<title>{0}</title>'.format(title))
  979. # Draw a background rectangle if necessary
  980. if background is not None:
  981. write('<path fill="{1}" d="M0 0h{0}v{0}h-{0}z"/>'
  982. .format(size, background))
  983. write_bytes(b'<path')
  984. if scale != 1:
  985. write(' transform="scale({0})"'.format(scale))
  986. if module_color is not None:
  987. write_bytes(b' stroke=')
  988. write(quoteattr(module_color))
  989. if lineclass is not None:
  990. write_bytes(b' class=')
  991. write(quoteattr(lineclass))
  992. write_bytes(b' d="')
  993. # Used to keep track of unknown/error coordinates.
  994. debug_path = ''
  995. # Current pen pointer position
  996. x, y = -quiet_zone, quiet_zone - .5 # .5 == stroke-width / 2
  997. wrote_bit = False
  998. # Loop through each row of the code
  999. for rnumber, row in enumerate(code):
  1000. start_column = 0 # Reset the starting column number
  1001. coord = '' # Reset row coordinates
  1002. y += 1 # Pen position on y-axis
  1003. length = 0 # Reset line length
  1004. # Examine every bit in the row
  1005. for colnumber, bit in enumerate(row):
  1006. if bit == 1:
  1007. length += 1
  1008. else:
  1009. if length:
  1010. x = start_column - x
  1011. coord += line(x, y, length, relative=wrote_bit)
  1012. x = start_column + length
  1013. y = 0 # y-axis won't change unless the row changes
  1014. length = 0
  1015. wrote_bit = True
  1016. start_column = colnumber + 1
  1017. if debug and bit != 0:
  1018. debug_path += errline(colnumber, rnumber)
  1019. if length:
  1020. x = start_column - x
  1021. coord += line(x, y, length, relative=wrote_bit)
  1022. x = start_column + length
  1023. wrote_bit = True
  1024. write(coord)
  1025. # Close path
  1026. write_bytes(b'"/>')
  1027. if debug and debug_path:
  1028. write_bytes(b'<path')
  1029. if scale != 1:
  1030. write(' transform="scale({0})"'.format(scale))
  1031. write(' class="pyqrerr" stroke="red" d="{0}"/>'.format(debug_path))
  1032. # Close document
  1033. write_bytes(b'</svg>\n')
  1034. if autoclose:
  1035. f.close()
  1036. def _png(code, version, file, scale=1, module_color=(0, 0, 0, 255),
  1037. background=(255, 255, 255, 255), quiet_zone=4, debug=False):
  1038. """See: pyqrcode.QRCode.png()
  1039. This function was abstracted away from QRCode to allow for the output of
  1040. QR codes during the build process, i.e. for debugging. It works
  1041. just the same except you must specify the code's version. This is needed
  1042. to calculate the PNG's size.
  1043. This method will write the given file out as a PNG file. Note, it
  1044. depends on the PyPNG module to do this.
  1045. :param module_color: Color of the QR code (default: ``(0, 0, 0, 255)`` (black))
  1046. :param background: Optional background color. If set to ``None`` the PNG
  1047. will have a transparent background.
  1048. (default: ``(255, 255, 255, 255)`` (white))
  1049. :param quiet_zone: Border around the QR code (also known as quiet zone)
  1050. (default: ``4``). Set to zero (``0``) if the code shouldn't
  1051. have a border.
  1052. :param debug: Inidicates if errors in the QR code should be added (as red
  1053. modules) to the output (default: ``False``).
  1054. """
  1055. import png
  1056. # Coerce scale parameter into an integer
  1057. try:
  1058. scale = int(scale)
  1059. except ValueError:
  1060. raise ValueError('The scale parameter must be an integer')
  1061. def scale_code(size):
  1062. """To perform the scaling we need to inflate the number of bits.
  1063. The PNG library expects all of the bits when it draws the PNG.
  1064. Effectively, we double, tripple, etc. the number of columns and
  1065. the number of rows.
  1066. """
  1067. # This is one row's worth of each possible module
  1068. # PNG's use 0 for black and 1 for white, this is the
  1069. # reverse of the QR standard
  1070. black = [0] * scale
  1071. white = [1] * scale
  1072. # Tuple to lookup colors
  1073. # The 3rd color is the module_color unless "debug" is enabled
  1074. colors = (white, black, (([2] * scale) if debug else black))
  1075. # Whitespace added on the left and right side
  1076. border_module = white * quiet_zone
  1077. # This is the row to show up at the top and bottom border
  1078. border_row = [[1] * size] * scale * quiet_zone
  1079. # This will hold the final PNG's bits
  1080. bits = []
  1081. # Add scale rows before the code as a border,
  1082. # as per the standard
  1083. bits.extend(border_row)
  1084. # Add each row of the to the final PNG bits
  1085. for row in code:
  1086. tmp_row = []
  1087. # Add one all white module to the beginning
  1088. # to create the vertical border
  1089. tmp_row.extend(border_module)
  1090. # Go through each bit in the code
  1091. for bit in row:
  1092. # Use the standard color or the "debug" color
  1093. tmp_row.extend(colors[(bit if bit in (0, 1) else 2)])
  1094. # Add one all white module to the end
  1095. # to create the vertical border
  1096. tmp_row.extend(border_module)
  1097. # Copy each row scale times
  1098. for n in range(scale):
  1099. bits.append(tmp_row)
  1100. # Add the bottom border
  1101. bits.extend(border_row)
  1102. return bits
  1103. def png_pallete_color(color):
  1104. """This creates a palette color from a list or tuple. The list or
  1105. tuple must be of length 3 (for rgb) or 4 (for rgba). The values
  1106. must be between 0 and 255. Note rgb colors will be given an added
  1107. alpha component set to 255.
  1108. The pallete color is represented as a list, this is what is returned.
  1109. """
  1110. if color is None:
  1111. return ()
  1112. if not isinstance(color, (tuple, list)):
  1113. r, g, b = _hex_to_rgb(color)
  1114. return r, g, b, 255
  1115. rgba = []
  1116. if not (3 <= len(color) <= 4):
  1117. raise ValueError('Colors must be a list or tuple of length '
  1118. ' 3 or 4. You passed in "{0}".'.format(color))
  1119. for c in color:
  1120. c = int(c)
  1121. if 0 <= c <= 255:
  1122. rgba.append(int(c))
  1123. else:
  1124. raise ValueError('Color components must be between 0 and 255')
  1125. # Make all colors have an alpha channel
  1126. if len(rgba) == 3:
  1127. rgba.append(255)
  1128. return tuple(rgba)
  1129. if module_color is None:
  1130. raise ValueError('The module_color must not be None')
  1131. bitdepth = 1
  1132. # foreground aka module color
  1133. fg_col = png_pallete_color(module_color)
  1134. transparent = background is None
  1135. # If background color is set to None, the inverse color of the
  1136. # foreground color is calculated
  1137. bg_col = png_pallete_color(background) if background is not None else tuple([255 - c for c in fg_col])
  1138. # Assume greyscale if module color is black and background color is white
  1139. greyscale = fg_col[:3] == (0, 0, 0) and (not debug and transparent or bg_col == (255, 255, 255, 255))
  1140. transparent_color = 1 if transparent and greyscale else None
  1141. palette = [fg_col, bg_col] if not greyscale else None
  1142. if debug:
  1143. # Add "red" as color for error modules
  1144. palette.append((255, 0, 0, 255))
  1145. bitdepth = 2
  1146. # The size of the PNG
  1147. size = _get_png_size(version, scale, quiet_zone)
  1148. # We need to increase the size of the code to match up to the
  1149. # scale parameter.
  1150. code_rows = scale_code(size)
  1151. # Write out the PNG
  1152. f, autoclose = _get_writable(file, 'wb')
  1153. w = png.Writer(width=size, height=size, greyscale=greyscale,
  1154. transparent=transparent_color, palette=palette,
  1155. bitdepth=bitdepth)
  1156. try:
  1157. w.write(f, code_rows)
  1158. finally:
  1159. if autoclose:
  1160. f.close()
  1161. def _eps(code, version, file_or_path, scale=1, module_color=(0, 0, 0),
  1162. background=None, quiet_zone=4):
  1163. """This function writes the QR code out as an EPS document. The
  1164. code is drawn by drawing only the modules corresponding to a 1. They
  1165. are drawn using a line, such that contiguous modules in a row
  1166. are drawn with a single line. The file parameter is used to
  1167. specify where to write the document to. It can either be a writable (text)
  1168. stream or a file path. The scale parameter is sets how large to draw
  1169. a single module. By default one point (1/72 inch) is used to draw a single
  1170. module. This may make the code to small to be read efficiently.
  1171. Increasing the scale will make the code larger. This function will accept
  1172. fractional scales (e.g. 2.5).
  1173. :param module_color: Color of the QR code (default: ``(0, 0, 0)`` (black))
  1174. The color can be specified as triple of floats (range: 0 .. 1) or
  1175. triple of integers (range: 0 .. 255) or as hexadecimal value (i.e.
  1176. ``#36c`` or ``#33B200``).
  1177. :param background: Optional background color.
  1178. (default: ``None`` (no background)). See `module_color` for the
  1179. supported values.
  1180. :param quiet_zone: Border around the QR code (also known as quiet zone)
  1181. (default: ``4``). Set to zero (``0``) if the code shouldn't
  1182. have a border.
  1183. """
  1184. from functools import partial
  1185. import time
  1186. import textwrap
  1187. def write_line(writemeth, content):
  1188. """\
  1189. Writes `content` and ``LF``.
  1190. """
  1191. # Postscript: Max. 255 characters per line
  1192. for line in textwrap.wrap(content, 255):
  1193. writemeth(line)
  1194. writemeth('\n')
  1195. def line(offset, length):
  1196. """\
  1197. Returns coordinates to draw a line with the provided length.
  1198. """
  1199. res = ''
  1200. if offset > 0:
  1201. res = ' {0} 0 m'.format(offset)
  1202. res += ' {0} 0 l'.format(length)
  1203. return res
  1204. def rgb_to_floats(color):
  1205. """\
  1206. Converts the provided color into an acceptable format for Postscript's
  1207. ``setrgbcolor``
  1208. """
  1209. def to_float(clr):
  1210. if isinstance(clr, float):
  1211. if not 0.0 <= clr <= 1.0:
  1212. raise ValueError('Invalid color "{0}". Not in range 0 .. 1'
  1213. .format(clr))
  1214. return clr
  1215. if not 0 <= clr <= 255:
  1216. raise ValueError('Invalid color "{0}". Not in range 0 .. 255'
  1217. .format(clr))
  1218. return 1/255.0 * clr if clr != 1 else clr
  1219. if not isinstance(color, (tuple, list)):
  1220. color = _hex_to_rgb(color)
  1221. return tuple([to_float(i) for i in color])
  1222. f, autoclose = _get_writable(file_or_path, 'w')
  1223. writeline = partial(write_line, f.write)
  1224. size = tables.version_size[version] * scale + (2 * quiet_zone * scale)
  1225. # Write common header
  1226. writeline('%!PS-Adobe-3.0 EPSF-3.0')
  1227. writeline('%%Creator: PyQRCode <https://pypi.python.org/pypi/PyQRCode/>')
  1228. writeline('%%CreationDate: {0}'.format(time.strftime("%Y-%m-%d %H:%M:%S")))
  1229. writeline('%%DocumentData: Clean7Bit')
  1230. writeline('%%BoundingBox: 0 0 {0} {0}'.format(size))
  1231. # Write the shortcuts
  1232. writeline('/M { moveto } bind def')
  1233. writeline('/m { rmoveto } bind def')
  1234. writeline('/l { rlineto } bind def')
  1235. mod_color = module_color if module_color == (0, 0, 0) else rgb_to_floats(module_color)
  1236. if background is not None:
  1237. writeline('{0:f} {1:f} {2:f} setrgbcolor clippath fill'
  1238. .format(*rgb_to_floats(background)))
  1239. if mod_color == (0, 0, 0):
  1240. # Reset RGB color back to black iff module color is black
  1241. # In case module color != black set the module RGB color later
  1242. writeline('0 0 0 setrgbcolor')
  1243. if mod_color != (0, 0, 0):
  1244. writeline('{0:f} {1:f} {2:f} setrgbcolor'.format(*mod_color))
  1245. if scale != 1:
  1246. writeline('{0} {0} scale'.format(scale))
  1247. writeline('newpath')
  1248. # Current pen position y-axis
  1249. # Note: 0, 0 = lower left corner in PS coordinate system
  1250. y = tables.version_size[version] + quiet_zone + .5 # .5 = linewidth / 2
  1251. last_bit = 1
  1252. # Loop through each row of the code
  1253. for row in code:
  1254. offset = 0 # Set x-offset of the pen
  1255. length = 0
  1256. y -= 1 # Move pen along y-axis
  1257. coord = '{0} {1} M'.format(quiet_zone, y) # Move pen to initial pos
  1258. for bit in row:
  1259. if bit != last_bit:
  1260. if length:
  1261. coord += line(offset, length)
  1262. offset = 0
  1263. length = 0
  1264. last_bit = bit
  1265. if bit == 1:
  1266. length += 1
  1267. else:
  1268. offset += 1
  1269. if length:
  1270. coord += line(offset, length)
  1271. writeline(coord)
  1272. writeline('stroke')
  1273. writeline('%%EOF')
  1274. if autoclose:
  1275. f.close()
  1276. def _hex_to_rgb(color):
  1277. """\
  1278. Helper function to convert a color provided in hexadecimal format
  1279. as RGB triple.
  1280. """
  1281. if color[0] == '#':
  1282. color = color[1:]
  1283. if len(color) == 3:
  1284. color = color[0] * 2 + color[1] * 2 + color[2] * 2
  1285. if len(color) != 6:
  1286. raise ValueError('Input #{0} is not in #RRGGBB format'.format(color))
  1287. return [int(n, 16) for n in (color[:2], color[2:4], color[4:])]