Giter Club home page Giter Club logo

python-qrcode's Introduction

Pure python QR Code generator

Generate QR codes.

A standard install uses pypng to generate PNG files and can also render QR codes directly to the console. A standard install is just:

pip install qrcode

For more image functionality, install qrcode with the pil dependency so that pillow is installed and can be used for generating images:

pip install "qrcode[pil]"

What is a QR Code?

A Quick Response code is a two-dimensional pictographic code used for its fast readability and comparatively large storage capacity. The code consists of black modules arranged in a square pattern on a white background. The information encoded can be made up of any kind of data (e.g., binary, alphanumeric, or Kanji symbols)

Usage

From the command line, use the installed qr script:

qr "Some text" > test.png

Or in Python, use the make shortcut function:

import qrcode
img = qrcode.make('Some data here')
type(img)  # qrcode.image.pil.PilImage
img.save("some_file.png")

Advanced Usage

For more control, use the QRCode class. For example:

import qrcode
qr = qrcode.QRCode(
    version=1,
    error_correction=qrcode.constants.ERROR_CORRECT_L,
    box_size=10,
    border=4,
)
qr.add_data('Some data')
qr.make(fit=True)

img = qr.make_image(fill_color="black", back_color="white")

The version parameter is an integer from 1 to 40 that controls the size of the QR Code (the smallest, version 1, is a 21x21 matrix). Set to None and use the fit parameter when making the code to determine this automatically.

fill_color and back_color can change the background and the painting color of the QR, when using the default image factory. Both parameters accept RGB color tuples.

img = qr.make_image(back_color=(255, 195, 235), fill_color=(55, 95, 35))

The error_correction parameter controls the error correction used for the QR Code. The following four constants are made available on the qrcode package:

ERROR_CORRECT_L

About 7% or less errors can be corrected.

ERROR_CORRECT_M (default)

About 15% or less errors can be corrected.

ERROR_CORRECT_Q

About 25% or less errors can be corrected.

ERROR_CORRECT_H.

About 30% or less errors can be corrected.

The box_size parameter controls how many pixels each "box" of the QR code is.

The border parameter controls how many boxes thick the border should be (the default is 4, which is the minimum according to the specs).

Other image factories

You can encode as SVG, or use a new pure Python image processor to encode to PNG images.

The Python examples below use the make shortcut. The same image_factory keyword argument is a valid option for the QRCode class for more advanced usage.

SVG

You can create the entire SVG or an SVG fragment. When building an entire SVG image, you can use the factory that combines as a path (recommended, and default for the script) or a factory that creates a simple set of rectangles.

From your command line:

qr --factory=svg-path "Some text" > test.svg
qr --factory=svg "Some text" > test.svg
qr --factory=svg-fragment "Some text" > test.svg

Or in Python:

import qrcode
import qrcode.image.svg

if method == 'basic':
    # Simple factory, just a set of rects.
    factory = qrcode.image.svg.SvgImage
elif method == 'fragment':
    # Fragment factory (also just a set of rects)
    factory = qrcode.image.svg.SvgFragmentImage
else:
    # Combined path factory, fixes white space that may occur when zooming
    factory = qrcode.image.svg.SvgPathImage

img = qrcode.make('Some data here', image_factory=factory)

Two other related factories are available that work the same, but also fill the background of the SVG with white:

qrcode.image.svg.SvgFillImage
qrcode.image.svg.SvgPathFillImage

The QRCode.make_image() method forwards additional keyword arguments to the underlying ElementTree XML library. This helps to fine tune the root element of the resulting SVG:

import qrcode
qr = qrcode.QRCode(image_factory=qrcode.image.svg.SvgPathImage)
qr.add_data('Some data')
qr.make(fit=True)

img = qr.make_image(attrib={'class': 'some-css-class'})

You can convert the SVG image into strings using the to_string() method. Additional keyword arguments are forwarded to ElementTrees tostring():

img.to_string(encoding='unicode')

Pure Python PNG

If Pillow is not installed, the default image factory will be a pure Python PNG encoder that uses pypng.

You can use the factory explicitly from your command line:

qr --factory=png "Some text" > test.png

Or in Python:

import qrcode
from qrcode.image.pure import PyPNGImage
img = qrcode.make('Some data here', image_factory=PyPNGImage)

Styled Image

Works only with versions >=7.2 (SVG styled images require 7.4).

To apply styles to the QRCode, use the StyledPilImage or one of the standard SVG image factories. These accept an optional module_drawer parameter to control the shape of the QR Code.

These QR Codes are not guaranteed to work with all readers, so do some experimentation and set the error correction to high (especially if embedding an image).

Other PIL module drawers:

image

For SVGs, use SvgSquareDrawer, SvgCircleDrawer, SvgPathSquareDrawer, or SvgPathCircleDrawer.

These all accept a size_ratio argument which allows for "gapped" squares or circles by reducing this less than the default of Decimal(1).

The StyledPilImage additionally accepts an optional color_mask parameter to change the colors of the QR Code, and an optional embeded_image_path to embed an image in the center of the code.

Other color masks:

image

Here is a code example to draw a QR code with rounded corners, radial gradient and an embedded image:

import qrcode
from qrcode.image.styledpil import StyledPilImage
from qrcode.image.styles.moduledrawers.pil import RoundedModuleDrawer
from qrcode.image.styles.colormasks import RadialGradiantColorMask

qr = qrcode.QRCode(error_correction=qrcode.constants.ERROR_CORRECT_L)
qr.add_data('Some data')

img_1 = qr.make_image(image_factory=StyledPilImage, module_drawer=RoundedModuleDrawer())
img_2 = qr.make_image(image_factory=StyledPilImage, color_mask=RadialGradiantColorMask())
img_3 = qr.make_image(image_factory=StyledPilImage, embeded_image_path="/path/to/image.png")

Examples

Get the text content from `print_ascii`:

import io
import qrcode
qr = qrcode.QRCode()
qr.add_data("Some text")
f = io.StringIO()
qr.print_ascii(out=f)
f.seek(0)
print(f.read())

The add_data method will append data to the current QR object. To add new data by replacing previous content in the same object, first use clear method:

import qrcode
qr = qrcode.QRCode()
qr.add_data('Some data')
img = qr.make_image()
qr.clear()
qr.add_data('New data')
other_img = qr.make_image()

Pipe ascii output to text file in command line:

qr --ascii "Some data" > "test.txt"
cat test.txt

Alternative to piping output to file to avoid PowerShell issues:

# qr "Some data" > test.png
qr --output=test.png "Some data"

python-qrcode's People

Contributors

adamw523 avatar agnat avatar alfreedom avatar brainy avatar cryptogun avatar digitaltembo avatar gadgetsteve avatar hughrawlinson avatar hugovk avatar hvitis avatar jmgs avatar koenbollen avatar malept avatar maribedran avatar mattiasj-axis avatar mgorny avatar mozillazg avatar mruffalo avatar ndevenish avatar nilam09 avatar paulo-raca avatar pedro-w avatar smileychris avatar tcely avatar timgates42 avatar viktorstiskala avatar warownia1 avatar welshjf avatar wolfgang42 avatar yeolar avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

python-qrcode's Issues

Numeric data

I can't figure out how to fit 10-digit number to version 1 qr-code:

DataOverflowError: Code length overflow. Data size (92) > size available (72)

According to the spec http://www.denso-wave.com/qrcode/vertable1-e.html it is possible for numeric data. Is there any examples of how to construct QR8bitByte instance from integer?

Change default image renderer

Currently, the default image renderer is PIL:
https://github.com/lincolnloop/python-qrcode/blob/master/qrcode/main.py#L251

The problem is that this requires external dependencies where they may not be needed. The SVG renderer does not generally require external dependencies and would be a good fit for a default renderer.

Changing this would allow a more modular dependency tree. See for instance the problem we are having here: https://bugzilla.redhat.com/show_bug.cgi?id=1117432

Test fail on Python 3.5

The unit tests are failing on Python 3.5 with the following message when pyimaging is not installed:

======================================================================
ERROR: pure (unittest.loader._FailedTest)
----------------------------------------------------------------------
ImportError: Failed to import test module: pure
Traceback (most recent call last):
  File "C:\User_Program_Files\Anaconda3\lib\unittest\loader.py", line 153, in loadTestsFromName
    module = __import__(module_name)
  File "C:\Users\username\Downloads\qrcode-5.2.2.tar\dist\qrcode-5.2.2\qrcode\image\pure.py", line 1, in <module>
    from pymaging import Image
ImportError: No module named 'pymaging'


======================================================================
ERROR: pure (unittest.loader._FailedTest)
----------------------------------------------------------------------
ImportError: Failed to import test module: pure
Traceback (most recent call last):
  File "C:\User_Program_Files\Anaconda3\lib\unittest\loader.py", line 153, in loadTestsFromName
    module = __import__(module_name)
  File "C:\Users\username\Downloads\qrcode-5.2.2.tar\dist\qrcode-5.2.2\qrcode\image\pure.py", line 1, in <module>
    from pymaging import Image
ImportError: No module named 'pymaging'

The tests work fine on all other versions of Python I have tested, but they fail identically on Python 3.5 on two different systems (openSUSE Linux and Anaconda for Windows).

Error generating qrcode with non ascii character

Hi,

with the 2.3 version i get the following error (with 2.0 this didn't happened):

import qrcode
qr_string = u'Acuña'
qrcode.make(qr_string)

Traceback (most recent call last):
File "", line 1, in
File "/usr/local/lib/python2.7/dist-packages/qrcode/main.py", line 12, in make
qr.add_data(data)
File "/usr/local/lib/python2.7/dist-packages/qrcode/main.py", line 42, in add_data
data = util.QRData(data)
File "/usr/local/lib/python2.7/dist-packages/qrcode/util.py", line 257, in init
data = str(data)
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf1' in position 3: ordinal not in range(128)

Thanks

PS: Great library!!

Performance is really slow for larger codes

Just as a heads-up, this library takes about one second to generate a version 20 qr code, and about 10 seconds for a version 40 code.

I've ended up having to use a python wrapper to libqrencode, with is several orders of magnitude faster. (less than 10 msec)

Requirement PIL/Pillow missing in setup.py

The requirement for PIL respective Pillow is missing, see below.

Name: qrcode
Version: 5.2.2

$ virtualenv foo
$ . foo/bin/activate
(foo) $ pip install qrcode
(foo) $ qr </tmp/x.txt > /tmp/x.png
Traceback (most recent call last):
  File "/tmp/foo/bin/qr", line 11, in <module>
    sys.exit(main())
  File "/tmp/foo/lib/python2.7/site-packages/qrcode/console_scripts.py", line 80, in main
    img = qr.make_image(image_factory=image_factory)
  File "/tmp/foo/lib/python2.7/site-packages/qrcode/main.py", line 263, in make_image
    from qrcode.image.pil import PilImage
  File "/tmp/foo/lib/python2.7/site-packages/qrcode/image/pil.py", line 8, in <module>
    import Image
ImportError: No module named Image

generate iQR codes

hi! I understand that this module generates standard qr codes. Can it be extended to generate iQR codes? (or micro QR code). Thanks!

Generated png is corrupted

It generates 435 bytes of png and it seems corrupted.
I tried:

qr "Some text" > test.png

qrcode library version: 5.1
python: 2.7
PIL: 1.1.7
OS: Windows 7 64bit

QRData.__repr__ broken in python3

util.QRData.__repr__ returns the underlying bytes, rather than a printable representation, which it got away with in python 2, but not 3. This dates back to the QR8bitByte class from the original PyQRNative.

>>> import qrcode
>>> qrcode.util.QRData('hello')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: __repr__ returned non-string (type bytes)

Easy fix: replace return self.data with return repr(self.data).

>>> qrcode.util.QRData('hello')
b'hello'

Note that this changes the behavior in python 2, returning the string in quotes instead of bare. I doubt anyone uses this other than for experimentation in the REPL like I was, and the change is more in line with what repr is "supposed" to do anyway ("For most object types, eval(repr(object)) == object").

Generating newline breaks

Hi,

Great project, thanks for all the work.

I had a question I was hoping you could answer. How can I generate newline breaks? For example:

img = qrcode.make('Here is some text.\nHere is more text on the next line')

Thanks in advance for the help.

Reading of first argument with non-UTF-8 characters fails with Python 3

Reading of first argument with non-UTF-8 characters with Python 3 triggers UnicodeEncodeError exception:

$ PYTHONPATH="." python3.4 qrcode/console_scripts.py $'\x80'
Traceback (most recent call last):
  File "qrcode/console_scripts.py", line 65, in <module>
    main()
  File "qrcode/console_scripts.py", line 52, in main
    qr.add_data(data)
  File "/tmp/python-qrcode/qrcode/main.py", line 58, in add_data
    self.data_list.extend(util.optimal_data_chunks(data))
  File "/tmp/python-qrcode/qrcode/util.py", line 315, in optimal_data_chunks
    data = to_bytestring(data)
  File "/tmp/python-qrcode/qrcode/util.py", line 354, in to_bytestring
    data = six.text_type(data).encode('utf-8')
UnicodeEncodeError: 'utf-8' codec can't encode character '\udc80' in position 0: surrogates not allowed

First argument should be encoded with surrogateescape error handler, since surrogates are used in sys.argv for non-UTF-8 characters:

$ python3.4 -c 'import sys; print(sys.argv); print([x.encode(errors="surrogateescape") for x in sys.argv])' $'\x80'
['-c', '\udc80']
[b'-c', b'\x80']

Fix:

--- qrcode/console_scripts.py
+++ qrcode/console_scripts.py
@@ -46,6 +46,8 @@

     if args:
         data = args[0]
+        if sys.version_info[0] >= 3:
+            data = data.encode(errors="surrogateescape")
     else:
         data = (sys.stdin.buffer if sys.version_info[0] >= 3 else sys.stdin).read()
     if opts.optimize is None:

Creating 4000 char. QR code

I have been trying to create a bar code with around 4000 Char. but it is failing with the following error

Traceback (most recent call last):
File "libqrenc.py", line 23, in
makeQr("s"*4000)
File "libqrenc.py", line 19, in makeQr
qr.make(fit=True)
File "/usr/lib/python2.7/site-packages/qrcode-2.3.1-py2.7.egg/qrcode/main.py", line 54, in make
self.best_fit(start=self.version)
File "/usr/lib/python2.7/site-packages/qrcode-2.3.1-py2.7.egg/qrcode/main.py", line 109, in best_fit
self.error_correction, self.data_list)
File "/usr/lib/python2.7/site-packages/qrcode-2.3.1-py2.7.egg/qrcode/util.py", line 402, in create_data
rs_blocks = base.rs_blocks(version, error_correction)
File "/usr/lib/python2.7/site-packages/qrcode-2.3.1-py2.7.egg/qrcode/base.py", line 344, in rs_blocks
rs_block = RS_BLOCK_TABLE[(version - 1) * 4 + offset]
IndexError: list index out of range

also the code is:

import qrcode

def verifyData(data):
    if len(data) > 4296:
        return 0
    else:
        return data

def makeQr(data):
    cleanData = verifyData(data)
    if not cleanData:
        return 0
    qr = qrcode.QRCode(
        version=None,
        error_correction=qrcode.constants.ERROR_CORRECT_H,
    )
    qr.add_data(cleanData)
    qr.make(fit=True)
    img = qr.make_image()
    img.save('/tmp/2.png',"PNG")

makeQr("s"*4000)

hyphen-used-as-minus-sign in man page

Here's a minor issue in the man page, as reported by the lintian tool run as part of Debian packaging:

I: python-qrcode: hyphen-used-as-minus-sign usr/share/man/man1/qr.1.gz:6
N: 
N:    This manual page seems to contain a hyphen where a minus sign was
N:    intended. By default, "-" chars are interpreted as hyphens (U+2010) by
N:    groff, not as minus signs (U+002D). Since options to programs use minus
N:    signs (U+002D), this means for example in UTF-8 locales that you cannot
N:    cut and paste options, nor search for them easily. The Debian groff
N:    package currently forces "-" to be interpreted as a minus sign due to
N:    the number of manual pages with this problem, but this is a
N:    Debian-specific modification and hopefully eventually can be removed.
N:    
N:    "-" must be escaped ("\-") to be interpreted as minus. If you really
N:    intend a hyphen (normally you don't), write it as "\(hy" to emphasise
N:    that fact. See groff(7) and especially groff_char(7) for details, and
N:    also the thread starting with
N:    http://lists.debian.org/debian-devel/2003/debian-devel-200303/msg01481.h
N:    tml
N:    
N:    If you use some tool that converts your documentation to groff format,
N:    this tag may indicate a bug in the tool. Some tools convert dashes of
N:    any kind to hyphens. The safe way of converting dashes is to convert
N:    them to "\-".
N:    
N:    Because this error can occur very often, Lintian shows only the first 10
N:    occurrences for each man page and give the number of suppressed
N:    occurrences. If you want to see all warnings, run Lintian with the
N:    -d/--debug option.
N:    
N:    Refer to /usr/share/doc/groff-base/README.Debian and the groff_char(7)
N:    manual page for details.
N:    
N:    Severity: wishlist, Certainty: possible
N:    
N:    Check: manpages, Type: binary

util.QRData: enable other encode.

I have problem using Chinese character, and after I change the source of :
data = data.encode('utf-8') to data = data.encode('gbk'), everything is ok.

Option for White Border

When generating a QR code with border set to 4, the border should be rendered as part of the QR matrix rather than just as a part of the image. As far as I can tell, self.modules does not include the border, and when people are using this library to generate a matrix and are not interested in the image it would be useful to have the border as part of the matrix.

GPS data

Is possible to encode qrcode with the TYPE: GEO ? for gps data ?

'six' dependency not installed from pypi using 'pip install', etc.

You can currently do pip install qrcode and it will install python-qrcode, but it will fail to download the six dependency. This can be fixed by changing the import in setup.py to use setuptools rather than distutils. setuptools will automatically handle the install_requires variable.

Structured appending [feature request]

As I understand it, the QR spec allows for splitting up data across multiple symbols for large messages or where spacial constraints are an issue. This sort of functionality would be an excellent addition!

Thanks for such a great library

QR-decoding?

I've got an image which I want to decode using Python. Is this python qr-code lib only for generating qr-code images, or also for decoding?

If this doesn't decode images, would you have a tip on which library I can use to decode the images? I'm having a hard time to decode the images in Python. All tips are welcome!

qr command line tool throw exception with python-2.6.6

# qr hello
Traceback (most recent call last):
  File "/usr/bin/qr", line 9, in <module>
    load_entry_point('qrcode==5.1', 'console_scripts', 'qr')()
  File "/usr/lib/python2.6/site-packages/qrcode-5.1-py2.6.egg/qrcode/console_scripts.py", line 56, in main
    qr.print_ascii(tty=True)
  File "/usr/lib/python2.6/site-packages/qrcode-5.1-py2.6.egg/qrcode/main.py", line 235, in print_ascii
    out.write(codes[pos])
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2588' in position 0: ordinal not in range(128)

Modify "out.write(codes[pos])" to "out.write(codes[pos].encode('utf-8'))" fixed this problem.

First column of QR code image is empty

Hi,
in main.py line 271:
for col in range(self.modules_count - 1, 0, -2):
should be:
for col in range(self.modules_count - 1, -1, -2):
because:

range(9,0,-2)
[9, 7, 5, 3, 1]

range(8,0,-2)
[8, 6, 4, 2]

and column 0 is skipped. May be need some more work to avoid out of range with index [col-c] = -1

Greetings!

Generation of image file fails with Python 3

Generation of image file with Python 3 triggers TypeError: must be str, not bytes exception:

$ PYTHONPATH="." python3.4 qrcode/console_scripts.py --help
Usage: qr - Convert stdin (or the first argument) to a QR Code.

When stdout is a tty the QR Code is printed to the terminal and when stdout is
a pipe to a file an image is written. The default image format is PNG.
...
$ PYTHONPATH="." python3.4 qrcode/console_scripts.py text
█████████████████████████████
█████████████████████████████
████ ▄▄▄▄▄ ███▄▄██ ▄▄▄▄▄ ████
████ █   █ █ ▀▄  █ █   █ ████
████ █▄▄▄█ █ ▄█▄ █ █▄▄▄█ ████
████▄▄▄▄▄▄▄█ █▄▀ █▄▄▄▄▄▄▄████
████ ▀▄ ▄ ▄██▄▀█ █▄ ▄  █▀████
████▄▀▄█ ▄▄▄▄█ ▄█▄█▀   ▄█████
█████▄██▄█▄▄ ▀▄ ▀ ▀█▄▄█ ▀████
████ ▄▄▄▄▄ █▀▀ ▀ ▀ ▄█▀ ▄█████
████ █   █ █  ▄█ ██ █ ▀▄█████
████ █▄▄▄█ █▄ ▄▄█▄█▀ █ ██████
████▄▄▄▄▄▄▄█▄▄█▄█▄██▄█▄▄█████
█████████████████████████████
▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀
$ PYTHONPATH="." python3.4 qrcode/console_scripts.py text > /tmp/image.png
Traceback (most recent call last):
  File "qrcode/console_scripts.py", line 65, in <module>
    main()
  File "qrcode/console_scripts.py", line 61, in main
    img.save(sys.stdout)
  File "/tmp/python-qrcode/qrcode/image/pil.py", line 32, in save
    self._img.save(stream, kind)
  File "/usr/lib64/python3.4/site-packages/PIL/Image.py", line 1685, in save
    save_handler(self, fp, filename)
  File "/usr/lib64/python3.4/site-packages/PIL/PngImagePlugin.py", line 631, in _save
    fp.write(_MAGIC)
TypeError: must be str, not bytes

Fix:

--- qrcode/console_scripts.py
+++ qrcode/console_scripts.py
@@ -58,7 +58,7 @@
         return

     img = qr.make_image(image_factory=image_factory)
-    img.save(sys.stdout)
+    img.save(sys.stdout.buffer if sys.version_info[0] >= 3 else sys.stdout)


 if __name__ == "__main__":

Creating SVG images on python-2.6 fails

looks like ET.register_namespace is not available prior to python-2.7.

$ qr --factory=svg "hello world"
Traceback (most recent call last):
  File "/usr/bin/qr", line 53, in <module>
    main(*sys.argv[1:])
  File "/usr/bin/qr", line 48, in main
    img = qr.make_image(image_factory=image_factory)
  File "/usr/lib/python2.6/site-packages/qrcode/main.py", line 180, in make_image
    im = image_factory(self.border, self.modules_count, self.box_size)
  File "/usr/lib/python2.6/site-packages/qrcode/image/svg.py", line 49, in __init__
    super(SvgImage, self).__init__(border, width, box_size)
  File "/usr/lib/python2.6/site-packages/qrcode/image/svg.py", line 17, in __init__
    ET.register_namespace("svg", self._SVG_namespace)
AttributeError: 'module' object has no attribute 'register_namespace'

Typo in name of qrcode.main.QRCode.sutup_position_adjust_pattern()

Name of qrcode.main.QRCode.sutup_position_adjust_pattern() contains typo.

Fix:

--- qrcode/main.py
+++ qrcode/main.py
@@ -86,7 +86,7 @@
         self.setup_position_probe_pattern(0, 0)
         self.setup_position_probe_pattern(self.modules_count - 7, 0)
         self.setup_position_probe_pattern(0, self.modules_count - 7)
-        self.sutup_position_adjust_pattern()
+        self.setup_position_adjust_pattern()
         self.setup_timing_pattern()
         self.setup_type_info(test, mask_pattern)

@@ -275,7 +275,7 @@
                 continue
             self.modules[6][c] = (c % 2 == 0)

-    def sutup_position_adjust_pattern(self):
+    def setup_position_adjust_pattern(self):
         pos = util.pattern_position(self.version)

         for i in range(len(pos)):

Using a StringIO instead of saving to a file.

I am hoping to convert your images to base64 png's in a web application.
However, I can't seem to get it working.

png_image_buffer = cStringIO.StringIO()
img.save(png_image_buffer)
encoded_image = base64.b64encode(png_image_buffer.getvalue())

Could it be that there is no support for doing it this way? I want to avoid having to right and then delete so many files in my project if I keep having to save them.

Invalid qrcodes generated for some strings containing comma (,)

The bug is in RE_ALPHA_NUM (in util.py) regexp and in alpha_pattern regexp in function optimal_data_chunks (also in util.py) which contains '+-.' sequence which in addition to '+', '-' and '.' also matches comma ',' (the sequence actually means: match any char from '+' (ascii 43) to '.' (ascii 46)).

Reading of stdin with non-UTF-8 characters fails with Python 3

Reading of stdin with non-UTF-8 characters with Python 3 triggers UnicodeDecodeError exception:

$ echo $'\x80' | PYTHONPATH="." python3.4 qrcode/console_scripts.py
Traceback (most recent call last):
  File "qrcode/console_scripts.py", line 65, in <module>
    main()
  File "qrcode/console_scripts.py", line 50, in main
    data = sys.stdin.read()
  File "/usr/lib64/python3.4/codecs.py", line 313, in decode
    (result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x80 in position 0: invalid start byte

Fix:

--- qrcode/console_scripts.py
+++ qrcode/console_scripts.py
@@ -47,7 +47,7 @@
     if args:
         data = args[0]
     else:
-        data = sys.stdin.read()
+        data = (sys.stdin.buffer if sys.version_info[0] >= 3 else sys.stdin).read()
     if opts.optimize is None:
         qr.add_data(data)
     else:
--- qrcode/tests/test_script.py
+++ qrcode/tests/test_script.py
@@ -1,3 +1,4 @@
+import sys
 try:
     import unittest2 as unittest
 except ImportError:
@@ -30,7 +31,7 @@
         mock_stdin.configure_mock(**{'read.return_value': 'testtext'})
         with mock.patch('sys.stdin', mock_stdin) as stdin:
             main([])
-            self.assertTrue(stdin.read.called)
+            self.assertTrue((stdin.buffer if sys.version_info[0] >= 3 else stdin).read.called)
         mock_print_ascii.assert_called_with(tty=True)

     @mock.patch('os.isatty', lambda *args: True)

Default output on iTerm2 cannot be recognised

What is looks like on iTerm2:

iterm2-qr

On OS X's default terminal looks:

terminal-qr

Seems it uses QRCode.print_ascii method but not print_tty.

print_tty looks much better on iTerm2:
iterm-tty

Why not using tty instead of ascii?

BTW: I'm using OS X 10.10 with newest iTerm2 + Solorized theme

MemoryError with negative box_size

Traceback (most recent call last):
File "/home/michi/Python/qrcodetests.py", line 13, in
img = qr.make_image()
File "build/bdist.linux-x86_64/egg/qrcode/main.py", line 267, in make_image
File "build/bdist.linux-x86_64/egg/qrcode/image/base.py", line 13, in init
File "build/bdist.linux-x86_64/egg/qrcode/image/pil.py", line 33, in new_image
File "build/bdist.linux-x86_64/egg/PIL/Image.py", line 2022, in new
MemoryError

Testscript:
import qrcode
from PIL import Image

qr = qrcode.QRCode(
version=1,
error_correction=qrcode.constants.ERROR_CORRECT_H,
box_size=-100,
border=20,
)
qr.add_data('vielzulangerstring')
qr.make(fit=True)
img = qr.make_image()

Negative box_size should throw something like "Invalid Parameter Exception" instead of "MemoryError"

TypeError with more than three capital letters

With "Python 3.2.3 (default, Apr 11 2012, 07:15:24) [MSC v.1500 32 bit (Intel)] on win32", the code fails on more than three capital letters from UTF-8 source.

Code:

# -*- coding: utf-8 -*-
import qrcode
qr = qrcode.QRCode(
    version=1,
    error_correction=qrcode.constants.ERROR_CORRECT_L,
    box_size=10,
    border=4,
)
qr.add_data( "SOME DATA" )
qr.make(fit=True)

Output:

> python test.py
Traceback (most recent call last):
  File "test.py", line 11, in <module>
    qr.make(fit=True)
  File "c:\Python32\lib\site-packages\qrcode-4.0.4-py3.2.egg\qrcode\main.py", line 62, in make
  File "c:\Python32\lib\site-packages\qrcode-4.0.4-py3.2.egg\qrcode\main.py", line 117, in best_fit
  File "c:\Python32\lib\site-packages\qrcode-4.0.4-py3.2.egg\qrcode\util.py", line 463, in create_da
  File "c:\Python32\lib\site-packages\qrcode-4.0.4-py3.2.egg\qrcode\util.py", line 349, in write
TypeError: expected an object with the buffer interface

Test failures with stdout redirected

Test suite has 2 failures when stdout is redirected (either to a file or a pipe (e.g. cat or less)).

$ python2.7 -m unittest discover
.................ss............
----------------------------------------------------------------------
Ran 31 tests in 2.908s

OK (skipped=2)
$ python2.7 -m unittest discover | cat
.................ss.......�PNG
▒
IHDR""u��IDATx���]j�0��[�>&�e�<;Хt��X��>▒gii�����r��������}��*T�
U��S�[���t��eU]���$)��a��$��z��SP�▒���F̬^_ב�zvo�Zn�B�H���OK�q�t@��d�M�V��j���s��~(s��uh�f��A��P���B��    �V��<�u�{��|��Ԃ���z��1�oU��)�=�b%�8� ���g���?e@RBz7zcx��:6E�\�Ը���/���2T���ΠƂz#\�T������$DPӽ��x��u
j�c:���=m^�N��S�<�+▒.b��Xw���
����_����Qs��V|�B�P��=���F�fIEND�B`�F�PNG�н%p�������SN�GV������u����
▒
IHDR""u��IDATx���]j�0��[�>&�e�<;Хt��X��>▒gii�����r��������}��*T�
U��S�[���t��eU]���$)��a��$��z��SP�▒���F̬^_ב�zvo�Zn�B�H���OK�q�t@��d�M�V��j���s��~(s��uh�f��A��P���B��    �V��<�u�{��|��Ԃ���z��1�oU��)�=�b%�8� ���g���?e@RBz7zcx��:6E�\�Ը���/���2T���ΠƂz#\�T������$DPӽ��x��u
j�c:���=m^�N��S�<�+▒.b��Xw���
����_����Qs��V|�B�P��=���F�fIEND�B`�..�PNGн%p�������SN�GV������u����
▒
IHDR""u��IDATx���]j�0��[�>&�e�<;Хt��X��>▒gii�����r��������}��*T�
U��S�[���t��eU]���$)��a��$��z��SP�▒���F̬^_ב�zvo�Zn�B�H���OK�q�t@��d�M�V��j���s��~(s��uh�f��A��P���B��    �V��<�u�{��|��Ԃ���z��1�oU��)�=�b%�8� ���g���?e@RBz7zcx��:6E�\�Ը���/���2T���ΠƂz#\�T������$DPӽ��x��u
j�c:���=m^�N��S�<�+▒.b��Xw���
����_����Qs��V|�B�P��=���F�fIEND�B`�F.�:5�н%p�������SN�GV������u����
======================================================================
FAIL: test_isatty (qrcode.tests.test_script.ScriptTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/usr/lib64/python2.7/site-packages/mock.py", line 1201, in patched
    return func(*args, **keywargs)
  File "/tmp/python-qrcode/qrcode/tests/test_script.py", line 19, in test_isatty
    mock_print_ascii.assert_called_with(tty=True)
  File "/usr/lib64/python2.7/site-packages/mock.py", line 831, in assert_called_with
    raise AssertionError('Expected call: %s\nNot called' % (expected,))
AssertionError: Expected call: print_ascii(tty=True)
Not called

======================================================================
FAIL: test_stdin (qrcode.tests.test_script.ScriptTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/usr/lib64/python2.7/site-packages/mock.py", line 1201, in patched
    return func(*args, **keywargs)
  File "/tmp/python-qrcode/qrcode/tests/test_script.py", line 34, in test_stdin
    mock_print_ascii.assert_called_with(tty=True)
  File "/usr/lib64/python2.7/site-packages/mock.py", line 831, in assert_called_with
    raise AssertionError('Expected call: %s\nNot called' % (expected,))
AssertionError: Expected call: print_ascii(tty=True)
Not called

----------------------------------------------------------------------
Ran 31 tests in 2.506s

FAILED (failures=2, skipped=2)

qrcode.tests.test_script.ScriptTest.test_isatty() and qrcode.tests.test_script.ScriptTest.test_stdin() are already configured to be called with os.isatty() mocked, however qrcode.console_scripts.main() uses sys.stdout.isatty().

Fix:

--- qrcode/console_scripts.py
+++ qrcode/console_scripts.py
@@ -5,6 +5,7 @@
 When stdout is a tty the QR Code is printed to the terminal and when stdout is
 a pipe to a file an image is written. The default image format is PNG.
 """
+import os
 import sys
 import optparse
 import qrcode
@@ -52,7 +53,7 @@
     else:
         qr.add_data(data, optimize=opts.optimize)

-    if image_factory is None and sys.stdout.isatty():
+    if image_factory is None and os.isatty(sys.stdout.fileno()):
         qr.print_ascii(tty=True)
         return

Create SVG wrapped in <g> tags instead of just <svg>

Currently all of the SVG factories (SvgFragmentImage, SvgImage, etc) generate a complete SVG file, wrapped in <svg>…</svg>. It would be nice if there was a published API for wrapping the result in <g>…</g> so it could be more easily embedded in an existing SVG.

If this would be considered for acceptance, I'll submit a PR which makes the wrapping element a class attribute and appropriate subclasses.

str/bytes issues with python3 (python 3.4.1)

When i try to create an image with:

import PIL
import qrcode

img = qrcode.make("Some data here")

with open("img.png", 'w') as imgfile:
img.save(imgfile)

Python gives my a TypeError: must be str not bytes

Am i not saving the image correctly?

Thank you!

Quite literally: It's not a bug [report], it's a feature [praise]!

The 'qr' ASCII output just saved me major frustration and time in the configuration of my smartphone's WiFi key 👍 and the best thing: I didn't even have to create and later securely erase an intermediate QRcode image file! :-)

What's the maximum data size it handles?

I'm trying to pass a QRCode Max size which is 2953 bytes and it doesn't let me, throwing an error that states.

'ValueError: Invalid version (was 41, expected 1 to 40)'

Which I don't understand. Thank you.

Incompatibility with numpy

Not so much an issue as a request - Pillow/PIL are generally very complete for the 'RGB' and 'L' image modes, but many of the manipulation routines do not work well with the '1' image mode. Would you be willing to switch to the 'L' image mode to increase compatibility with those PIL features as well as image conversion to numpy arrays?

It's a single character change - line 21 of PIL.py changes to
"img = Image.new("L", (self.pixel_size, self.pixel_size), "white")"

Thanks,

Jake

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.