Giter VIP home page Giter VIP logo

pyqrcode's Introduction

pyqrcode

The pyqrcode module is a QR code generator that is simple to use and written in pure python. The module can automates most of the building process for creating QR codes. Most codes can be created using only two lines of code!

Unlike other generators, all of the helpers can be controlled manually. You are free to set any or all of the properties of your QR code.

QR codes can be saved as SVG, XBM, EPS, PNG (by using the pypng module), or plain text. They can also be displayed directly in most Linux terminal emulators and Tkinter. PIL is not used to render the image files.

The pyqrcode module attempts to follow the QR code standard as closely as possible. The terminology and the encodings used in pyqrcode come directly from the standard. This module also follows the algorithm laid out in the standard.

Requirements

The pyqrcode module only requires Python 2.6, Python 2.7, or Python 3. You may want to install pypng in order to render PNG files, but it is optional.

Installation

Installation is simple. It can be installed from pip using the following command:

$ pip install pyqrcode

Or from the code

$ python setup.py install

Usage

This is the only import you need. The heart of the module is the QRCode class. You can construct the class normally, or use the create wrapper function.

>>> import pyqrcode
>>> qr = pyqrcode.create('Unladden swallow')
>>> qr.png('famous-joke.png', scale=5)

PyPi

Encoding Data

This module supports all four encodings for data: numeric, alphanumeric, kanji, and binary.

The numeric type is the most efficient way to encode digits. As the name implies it is designed to encode integers. Some numbers might be two large, the object can use a string containing only digits instead of an actual number.

>>> number = pyqrcode.create(123456789012345)

The alphanumeric type is very limited in that it can only encode some ASCII characters. It encodes: uppercase letters, 0-9, the horizontal space, and eight punctuation characters. The available characters will let you encode a URL

>>> url = pyqrcode.create('http://uca.edu')

When all else fails the data can be encoded in pure binary. The quotation below must be encoded in binary because of the lower-cased characters, the apostrophe and the new line character.

>>> life = pyqrcode.create('''MR. CREOSOTE: Better get a bucket. I'm going to throw up.
    MAITRE D: Uh, Gaston! A bucket for monsieur. There you are, monsieur.''')

The only unimplemented encoding is ECI mode which allows for multiple encodings in one QR code (this will be implemented in a future version).

Manually Setting The QR Code's Properties

There are many situation where you might wish to have more fine grained control over how the QR Code is generated. You can specify all the properties of your QR code through the create function. There are three main properties to a QR code.

The error parameter sets the error correction level of the code. Each level has an associated name given by a letter: L, M, Q, or H; each level can correct up to 7, 15, 25, or 30 percent of the data respectively. There are several ways to specify the level, see pyqrcode.tables.modes for all the possible values. By default this parameter is set to 'H' which is the highest possible error correction, but it has the smallest available data capacity.

The version parameter specifies the size and data capacity of the code. Versions are any integer between 1 and 40, where version 1 is the smallest QR code, and version 40 is the largest. By default, the object uses the data's encoding and error correction level to calculate the smallest possible version. You may want to specify this parameter for consistency when generating several QR codes with varying amounts of data. That way all of the generated codes would have the same size.

Finally, the mode parameter sets how the contents will be encoded. As mentioned above, three of the five possible encodings have been written. By default the object uses the most efficient encoding for the contents. You can change this though. See qrcode.tables.modes for a list of possible values for this parameter.

The code below constructs a QR code with 25% error correction, size 27, and forces the encoding to be binary (rather than numeric).

>>> big_code = pyqrcode.create('0987654321', error='L', version=27, mode='binary')

Rendering

There are many possible formats for rendering the QR Code. The first is to render it as a string of 1's and 0's. This is method is used to help end users create their own renderer. It is also possible to print the code such that it is directly displayable in most Linux terminals. There are several image based renderers.

The terminal renderer outputs a string of ASCII escape codes that when displayed in a compatible terminal, will display a valid QR code. The background and module colors are settable (although as with any time you display colors in the terminal, there are several caveats).

>>> print(url.terminal())
>>> print(url.terminal('red', 'white'))

The SVG renderer outputs the QR Code as a scalable vector graphic. This renderer does not require any external modules. Instead it hand draws the QR code as a set paths.

>>> url.svg(sys.stdout, scale=1)
>>> url.svg('uca.svg', scale=4, module_color="#7D007D")

Alternatively, if you install the pypng module, you can render the QR Code to a PNG file. Colors should be specified as RGB or RGBA if you want to take advantage of transparency.

>>> number.png('big-number.png')
>>> life.png('sketch.png', scale=6, module_color=(0, 0, 0, 128), background=(0xff, 0xff, 0xcc))

Finally, there is a text based renderer. This will output the QR code as a string of 1's and 0's, with each row of the code on a new line.

>>> print(number.text())

pyqrcode's People

Contributors

broamski avatar heuer avatar luzfcb avatar marcobiscaro2112 avatar mnooner256 avatar zhicheng 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

pyqrcode's Issues

pypng is an unlisted dependency

Pretty much the subject.

I installed this with pip3 install --user pyqrcode but got hit with module not found on line 1266 of builder.py: import png. The comments to that file state that pypng is required, so I installed that the same way I installed pyqrcode and now it works.

Storing ANSI/ISO-8859-1 in QR Code

I have a hex string
hexString = "22fd30df7c13fb69f7f87e3a8728f0daf6ab360b82ec9e6d8c1157e19add4013080b3399eff31644e24553e9c30b697078492d9da33bf0a9235ab87a7662398a06c782a31acfc79c5023344b11f3750bb98e500b01"
ansi = bytes.fromhex(hexString ).decode('ANSI')

version = 8
scalepermodule = 10
r_image = 'bigcode_r_{}_{}_m.png'.format(version, scalepermodule)

bigcode_r = pyqrcode.create(ansi , error='M', version=version,mode='binary')
bigcode_r.png(r_image, scale=scalepermodule, module_color=[0, 0, 0], background = [0xff,0,0])

Keep getting error:
UnicodeEncodeError: 'latin-1' codec can't encode character '\u0131' in position 1: ordinal not in range(256)

How can I solve this?

Too much data for this code version.

Im using pythong 2.7.8 and django 1.6.5 (dont care about django)
I need to dynamically create 2 QR-files (png and svg):

url = 'http://test.com/test/myproject/name/etc/1/'  # tried with %s' % pk  , does not matter
data = QRCode(url)

hello exceptions:

if current_byte < len(data):
    raise ValueError('Too much data for this code version.')

but.. if i change code like this

data = QRCode('http://test.com/test/myproject/name/etc/1/')

all works fine, but looks the same, right? what problem with string variable ?

then i changed builder.py like this:

# if current_byte < len(data):
#    raise ValueError('Too much data for this code version.')

and all works fine with 1st version.

where I was wrong?

How to get message code words?

Hi,
Thanks for this awesome library.
I'm working on message code words. How to get message code words or error code words in binary/hexadecimal?
Are data_blocks is same as message code words?
Please suggest.
Thanks!!

Finding the settings for a given QR Code?

This is going to be a bit of a dozy, but what if we needed to find the embedded settings for a QR code?

For example, if I wanted to replicate QR codes based on some settings where I know what the code returns?

For example, the given qr code returns 2468 as the embedid code.

screenshot 47

Is there anyway I can find out what settings were used to make it so that I can replicate them?

Thanks!

width and height attributes of generated svg are huge

runing

`#!/usr/bin/python
import sys
import pyqrcode
text = sys.argv[1]
scale = sys.argv[2]
err_prt = sys.argv[3]
url = pyqrcode.create(text,err_prt) # error_protection in ['L','M','H'] -- Low make code smaller
url.svg(sys.stdout, scale, module_color="black", quiet_zone=1)
exit(0)`

with 'text' 3 'M'
returns
<svg xmlns="http://www.w3.org/2000/svg" height="333333...." width="33333...."> <path></path> </svg>

I resolved this remeasuring o client side but ... maybe I am wrong

for latest code see pyqrcodeNG - outstanding pull requests

I ended up spending a bit of time looking at this before realizing that this project has not been active for the last 4 years and newer code is available.

TL'DR

pip install pyqrcodeng

will get latest code from https://github.com/pyqrcode/pyqrcodeNG with the same API as this project (note that repo as of 2020 is now officially unmaintained but the code is ahead of this repo and includes PRs made against this repo which are open).

Also consider https://github.com/heuer/segno which is maintained.

Thanks everyone who contributed to this project especially Michael who spent the time to get this started, polished and shared out.

License?

Repository and distribution provides no license information.

Accoding to PyPy this lib is licensed under LGPL.

Maybe switch to BSD? :)

Anyway, the repository should contain a LICENSE file

"shiftjis" printed to terminal when creating qr-codes (windows-only)

I noticed that when calling pyqrcode.create() the string "shiftjis" is printed to the terminal.
I know that shiftjis is an encoding (not sure it is the right one for what I am doing) but even so, I don't think the create method should be printing out anything as it takes away control from the user of the library, if they want to know the encoding they can put a print statement into their code.

The message is definitely coming from line 158, which is the only print statement in the entire file. It appears to be a debug line left their by mistake.

Strangely, this problem only occurs when running on windows.

automatic version is too small

If I understand correctly, create should find the smallest QR code that can contain the data.

import pyqrcode
pyqrcode.create("6010102401", error="H")

produces

ValueError: The supplied data will not fit within this version of a QR code.

This works great:

pyqrcode.create("6010102401", error="H", version=2)

No longer working on python 2.7.9

The version after the commit eb4dd81 (fixing stream closing issues) produces empty qr codes on python version 2.7.9

Code example to test with:

import pyqrcode
import base64
import io

qrdata = pyqrcode.create("Wim")
raw = io.BytesIO()
qrdata.png("wim.png", scale=8)
qrdata.png(raw, scale=8)

print "|" + base64.b64encode(raw.getvalue()) + "|"

PyQRCode 2.0?

Since you introduced backward incompatible changes (i.e. border vs. quiet_zone) you may want to use 2.0 as next version rather than 1.1, see http://semver.org/

Drop Python2 Support

Python2 is EOL hence I believe it would make sense to drop its support and do some code cleanup along the way.

Generate base64 encode png image to use on src in <img> html tag

Hello, first, thanks for this.
I need to generate a qr code to be dynamically included in an HTML <img src="data:image/png;base64,......> tag in a Django app.

I would like to avoid any hard disk operation.

This feature already exists somewhere in this library?
if not, you can provide me a example of how can I get the code qr encoded in base64 format compatible with browser?

this would be a very useful feature.

Thanks.

only produce the path element, not the whole file

I would like to embed the QR svg element produced by this library in my own svg producing software, and the only way I see to do that, is to write the file into a StringIO, then extracting the element I need.

according to the docstring for QRCode.svg,

If only the code itself is desired, set the xmldecl to false. This will result in a fragment that contains only the "drawn" portion of the code.

however, if I do that, I only get rid of the leading <?xml version="1.0" encoding="UTF-8"?>, not also the root svg element. I would like the naked path element, and I would like it returned in a string, not written to a file.

non ascii characters

There is some problem with special characters. It seems that special characters like é, ö, è, ü, etc. are not represented in the qr-image.

ValueError: buffer size must be a multiple of element size

Trying to feed a PNG buffer to np.frombuffer and getting a buffer size error.

New to Python... would someone happen to know what is going on and how to fix this?

from cv2 import cv2
import pyqrcode
import io
import numpy as np
import sys

buffer = io.BytesIO()
qr = pyqrcode.create("foo")
qr.png(buffer, scale=2)

array = np.frombuffer(buffer.getvalue())
image = cv2.imdecode(array, cv2.IMREAD_COLOR)

cv2.imshow('QR code', image)
cv2.waitKey(0)
cv2.destroyAllWindows()

sys.exit()

Thanks!

Tag releases

Hi,
can you please use the tag function of git/github to tag new releases? This would make it much easier for PKGBUILDs to download the correct version from github. Thanks :)

@mnooner256

Skip detecting content type if constructor mode is given to constructor

The _detect_content_type method (called by the QRCode constructor) is dependant on the shiftjis encoding being present. On some Python installations this code will fail (we have a minimal Python setup with buildroot, excluding the Japanese and Chinese encodings to save file storage space).

I want the QRCode constructor to survive this condition by reverting back to 'binary' encoding.

Doesn't recognize Cyrillic

How can I make the module recognize the Cyrillic alphabet?

My code:
image = pyqrcode.create('АБВГД', encoding='UTF-8') image.png(fileName, scale=4)
When scanning, it gives out question marks "?????"

Rounded edges and Dots

Hi,

Is there a way to make the edges round and use dots instead of lines?
I am trying to achieve this look on a svg format without the logo part.
target qr code

Any help will be pretty much appreciated as I am kind of desperate.
Thanks,

Update the QRcode?

This is by far the best QRcode tool in python I can find, except this minor problem...
After I create the object using code = pyqrcode.create("somedata"), I find no way to change the data once the object is created. In other words, there is no function like update(self, data), which allows the data to be updated.

PS. I have tried to change the content through code.content = "something different", but it doesn't change anything. After I read the code I know this is not possible because there is no function in the class QRcode that could update the backend builder class.

I know I can simply create a new object with different content, but isn't it better to reuse the object?

[DISCUSS] Feature PR: Output as base64

I wanted to discuss this feature PR before actually taking any action.

One application I wanted was to be able to take the generated QR code and display it on an HTML page, without writing anything to disk.

As it turns out, this is possible:

# mytext was created
qrcode = pq.create(mytext)
buffer = BytesIO()
qrcode.png(buffer, scale=5)
enc = b64encode(buffer.getvalue()).decode('utf-8')

I was wondering if you might be interested in accepting a PR that defines the following API?

encoding = qrcode.base64(scale=5)

The underlying implementation would essentially use the aforementioned code:

# This is a class method
def base64(self, scale=5):
    buffer = BytesIO()
    self.png(buffer, scale=scale)
    enc = b64encode(buffer.getvalue()).decode('utf-8')

Please let me know, I'm happy to work on the PR for this. Alternatively, if you're not interested in this, no hard feelings too 😄.

QR code in dxf

QRcode
I would like to use a CNC machine to engrave qr code with a cylindrical milling cutter 2 sizes.
Would it be possible to have a dxf file of the tool path allowing to obtain a machining image as given in the attached file?

pyqrcode in RhinoPython - Grasshopper

I received the following report via email. I am moving the conversation over to github for posterity...

Some days ago I tried to run pyqrcode from Rhino Python in my Rhino (64-bit) but i could not import the pyqrcode library. I tried to change the path but nothing changed. The message that i receive is:

Message: No module named pyqrcode

Traceback:
line 1, in , "C:\Users\MEDINA\AppData\Local\Temp\TempScript.py"

How can I fix this issue?

Looking forward your response

Unicode data does not work

>>> import pyqrcode
>>> c = pyqrcode.create('Märchenbuch')
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "/[...]/pyqrcode/__init__.py", line 78, in create
    return QRCode(content, error, version, mode)
  File "/[...]/pyqrcode/__init__.py", line 143, in __init__
    self.version = self._pick_best_fit()
  File "/[...]/pyqrcode/__init__.py", line 211, in _pick_best_fit
    capacity >= len(self.data.encode('ascii'))) or \
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe4' in position 1: ordinal not in range(128)

Using a writeable stream

Under Python 2.7.6 I get:

Traceback (most recent call last):
File "", line 6, in
ValueError: I/O operation on closed file.

using the code:

import pyqrcode
from io import BytesIO
qr = pyqrcode.create("my qr string", mode='binary', version=7)
f=BytesIO()
qr.png(f, scale=4)
f.getvalue()

The code runs fine if I save the file to disk using:

qr.png("myqr.png", scale=4)

I tried hard to debug this but I can't find where the stream is being closed and there is not any .close() statement for the stream. [1]

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.