Click here to Skip to main content
14,578,796 members

QR Code Encoder and Decoder .NET(Framework, Standard, Core) Class Library Written in C# (Ver. 2.1.0)

Rate this:
4.96 (97 votes)
Please Sign up or sign in to vote.
4.96 (97 votes)
24 Jul 2019CPOL
The QR Code libraries allows your program to create (encode) QR Code image or, read (decode) an image containing one or more QR Codes. The attached source code is made of two solutions, a QR Code Encoder solution and a QR Code decoder solution.

QRCodeLibrary Icon

Introduction

The QR Code libraries allows your program to create (encode) QR Code image or, read (decode) an image containing one or more QR Codes. The attached source code is made of two solutions, a QR Code Encoder solution and a QR Code decoder solution. The encoder solution targets .NET framework (net462) and .NET standard (netstandard2.0). The decoder solution targets .NET framework (net462). The source code is written in C#. It is an open source code. The source downloads attached to this article include two libraries and four demo/test applications.

Version 2.1.0 Support was added for ECI Assignment Number. The assignment number range is zero to 999999. The number is not part of the QR Code data. It is used for encoding data subject to alternative interpretations of byte values (e.g. alternative character sets).

Encoder solution

  • QRCodeEncoderLibrary: A library exposing QR Code encoder and command line encoder. Visual studio will produce two DLL files one for net462 and one for netstandardapp2.0.
  • QRCodeEncoderDemo: A Windows Form demo program showing how to encode a string or a byte array into a QR Code image file.
  • QRCodeConsoleDemo: A Console .NET Core demo program showing how to encode a text file or a binary file into a QR Code image file.

Decoder solution

  • QRCodeDecoderLibrary: A library exposing QR Code decoder. Visual studio will produce one DLL for .NET framework (net462).
  • QRCodeDecoderDemo: A demo program showing how to decode Bitmap image of a QR Code and retrieve the string or byte array
  • QRCodeVideoDecoder: A demo program combining QR Code decoder and video camera image capture. The video camera software is based on Direct Show Library. Please note section QR Code Video Decoder at the bottom of this article.

The QR Code encoder part of this library is includer in the PDF File Writer C# Class Library article.

Installation

The open source code attached is made of two Visual Studio solutions. Each solution is made of one library project and two demo/test projects. As described above.

Integrating the code to your application requires the following steps. Install either the QRCodeEncoderLibrary.dll or the QRCodeDecoderLibrary.dll in your development area. Start the Visual Studio C# program and open your application. Go to the Solution Explorer, right click on References and select Add Reference. Select the Browse tab and navigate your file system to the location of the required library. When your application is published, the relevant library file must be included and installed in the same folder as your executable (.exe) file.

The relevant "using" statement must be added to all your source files:

using QRCodeEncoderLibrary;
// or
Using QRCodeDecoderLibrary;

QR Code

QR Code stands for Quick Response Code. It is a two-dimensional barcode. Visually, it is a square made of small black and white square modules. The square is surrounded by a white quite zone. The QR Code is defined by the international standard ISO/IEC 18004. A free copy of this standard is available here.

The ISO standard document defines the QR Code as “QR Code is a matrix consisting of an array of nominally square modules arranged in an overall square pattern, including a unique finder pattern located at three corners of the symbol and intended to assist in easy location of its position, size and inclination. A wide range of sizes of symbol is provided for together with four levels of error correction. Module dimensions are user-specified to enable symbol production by a wide variety of techniques.”

The ISO standard 18004 is the best source of information for understanding the details of the QR Code. Searching the internet yields many more articles on this subject. Wikipedia article about QR Code can be viewed here.

The QR Code standard is a collection of 40 different squares varying in size. Each square has a version number from 1 to 40. The size of each square varies from 21 by 21 modules (version 1) to 177 by 177 modules (version 40). Each version has 4 more modules per side than the previous version.

Square-Dimension = 21 + 4 * (Version - 1)

Some of the modules are fixed. The most obvious ones are the three-square finders. The remaining modules are divided between data and error correction. There are 4 levels of error correction:

  • L- Low will correct up to 7% errors
  • M- Medium will correct up to 15% errors
  • Q- Quarter will correct up to 25% errors
  • H- High will correct up to 30% errors

Each module in the data area represent one bit. Black module is 1 and white module is 0. The data area can be divided into segments. Each input segment byte array is encoded to data bits in one of three ways as described below. Note: The QR Code standard has one more encoding method for Kanji characters. It is not supported by this project.

  • Numeric data: The segment is made only of digits 0 – 9. Three digits will be converted to 10 bits.
  • Alphanumeric data: The segment is made of digits 0 - 9, upper case letters A -Z, and nine other characters: [space, $ % * + - . / :]. Two alphanumeric characters will be converted to 11 bits.
  • 8-bit byte data. The segment is not converted. There is one to one correspondence between input bits and modules.

To encode a QR Code, you supply the data to be encoded and one of the four error correction codes. The system will calculate the smallest version number required to represent the data.

The program analyzes each segment to find the "best" encoding. If you want to reduce the size of the QR Code and you have long strings of digits or alphanumeric data as defined above, then break your input into several strings or byte arrays. Some of these strings must be numeric only or Alphanumeric as defined above. During the decoding process, all resulted string segments will be concatenated together.

When the library decodes an image containing one or more QR Codes, the result will be an array of strings or array of byte arrays. Each array item is one QR Code.

QR Code Encoding

The main class for encoding is QREncoder. It will convert a byte array or a text string into a QR Code image. To create a QR Code image, follow the steps below:

Create QREncoder object. Set the four optional parameters. This object is reusable. If you want to create many QR Codes, just reuse this object. There is no initialization or dispose requirement. The four optional parameters will keep their value from the last run.

// create QR Code encoder object
QRCodeEncoder Encoder = new QREncoder();

Set the four optional parameters if required

// Error correction
// error correction low (7%)
Encoder.ErrorCorrection = ErrorCorrection.L;

// or
// error correction medium (15%) The Default
Encoder.ErrorCorrection = ErrorCorrection.M;

// or
// error correction quarter (25%)
Encoder.ErrorCorrection = ErrorCorrection.Q;

// or
// error correction high (30%)
Encoder.ErrorCorrection = ErrorCorrection.M;

// module size in pixels (default is 2)
Encoder.ModuleSize = 2;

// Quiet zone around the symbol (default is 8)
// Quiet zone must be at least 4 times the module size
Encoder.QuietZone = 8;

// ECI Assignment Value (default is -1 not used)
// The ECI value is a number in the range of 0 to 999999.
// or -1 if it is not used
Encoder.ECIAssignValue = -1; 

Higher error correction percentage gives you better protection against damaged QR Code images. The cost is the size of the QR symbol.

Call one of the four Encode methods:

// single text string input
public void Encode(string StringDataSegment);

// multiple text strings input
public void Encode(string[] StringDataSegments);

// single byte array input
public void Encode(byte[] ByteDataSegment);

// multiple byte arrays input
public void Encode(byte[][] ByteDataSegments);

If input data is text string, or array of text strings. The text will be converted to byte array using the following method.

// the encoder converts text string to byte array using the conversion below
byte[] ByteArray = Encoding.UTF8.GetBytes(Text);

Effectively, the library software will convert the first and second Encode methods to the third and fourth methods respectively.

The QRCodeEncoderLibrary will scan each incoming data byte array segment to determine the best encoding method. The program will not attempt to break a single segment to minimize the size of the QR Code matrix. You can submit array of segments in such a way as to take advantage of long strings of numeric or alphanumeric data.

The Encode method has no return value. If encoding is successful, a two-dimensional bool array (QRCodeMatrix) representing a QR Code image is saved within the Encode class. If encoding fails, an exception will be thrown. The QRCodeMatrix is a square array. Black modules are true and white modules are false. The matrix dimension is given in QRCodeEncoder.QRCodeDimension.

The next step is to save the QR Code symbol to a file or, to create a Bitmap. The example below shows how to create QR Code image file with the content "QR Code Library Project".

// create QREncoder object
QREncoder Encoder = new QREncoder()

// set optional parameters
Encoder.ErrorCorrection = ErrorCorrection.Q;
Encoder.ModuleSize = 4;
Encoder.QuietZone = 16;

// encode input text string 
// Note: there are 4 Encode methods in total
Encode("QR Code barcode example text string");

// save the barcode to PNG file
// This method DOES NOT use Bitmap class and is suitable for net-core and net-standard
// It produces files significantly smaller than SaveQRCodeToFile.
Encoder.SaveQRCodeToPngFile("File-Name");

// or
// save barcode image to an open stream
Encoder.SaveQRCodeToPngFile(OutputStream);

// or
// save barcode image to file using Bitmap class
// this is for net-framework and not for net-code or net-standard
// you can produce PNG file but consider the QRCOdeToPngFile method above.
Encoder.SaveQRCodeToFile("File-Name", ImageFormat);

// or
// save barcode image to an open stream
Encoder.SaveQRCodeToFile(OutputStream, ImageFormat);

// or
// create Bitmap class (net-framework only)
Bitmap bitmap = CreateQRCodeBitmap();

// or
// create Bitmap class with different colors (net-framework only)
Bitmap bitmap = CreateQRCodeBitmap(WhiteBrush, BlackBrush);

// or
// create bool array of image pixels
Bool[,] ImagePixels = ConvertQRCodeMatrixToPixels();

Create PNG image file using the CommandLine class.

The command line arguments are described below. A more detail description of each option is given above.

Command line arguments format
[optional arguments] input-file output-file
Output file must have .png extension
Options format /code:value or -code:value (the : can be =)
Error correction level. code=[error|e], value=low|l|medium|m|quarter|q|high|h], default=m
Module size. code=[module|m], value=[1-100], default=2
Quiet zone. code=[quiet|q], value=[4-400], default=8, min=4*width
Text file format. code=[text|t] see notes below
Input file is binary unless text file option is specified
If input file format is text or t, the string will be encoded to byte array

QR Code Decoding

The QRDecoder converts QR Code Bitmap images into an array of byte arrays. If  the QR Code image contains optional ECI Assignment Value it can be retrived as noted below.  To decode a Bitmap containing one or more QR Code images, follow the steps below.

Create QRDecoder object. This object is reusable. If you want to create many QR Codes, just reuse this object. There is no initialization or dispose requirement. And call the ImageDecoder method.

// create QR Code decoder object
QRDecoder Decoder = new QRDecoder();

// call image decoder methos with <code>Bitmap</code> image of QRCode barcode
byte[][] DataByteArray = Decoder.ImageDecoder(InputImage)

// get the ECI Assignment value
ECIValue = Decoder.ECIAssignValue;
if(ECIValue == -1)
    {
    // Assignment value not defined
    }
else
    {
    // Assignment value between 0 to 999999
    }

If DataByteArray is null, no QR Code was detected within the Bitmap. If DataByteArray length is one, one QR Code was found. If DataByteArray length is more than one, there were more than one QR Code images within the Bitmap. Each QR Code image is represented by a byte array. To convert a byte array to string use:

// convert binary result to text string
string Result = QRCode.ByteArrayToStr(DataByteArray[Index]);

The ByteArrayToStr method converts byte array into string in the following way:

// The QRDecoder converts byte array to text string the class using this conversion
public static string ByteArrayToStr(byte[] DataArray)
	{
	Decoder = Encoding.UTF8.GetDecoder();
	int CharCount = Decoder.GetCharCount(DataArray, 0, DataArray.Length);
	char[] CharArray = new char[CharCount];
	Decoder.GetChars(DataArray, 0, DataArray.Length, CharArray, 0);
	return new string(CharArray);
	}

For example, the image below is of two QR Codes one within the other. The big one data is: Big QR Code, the small one data is: Small QR Code. The big one has error correction set to High. The program will find both QR Codes and recover the missing area of the big one using error correction to get the correct content.

QR Code Example

QR Code 1
Big QR Code
QR Code 2
Small QR Code

Another example of three QR Codes. The decoder finds 9 finders in the picture. All possible 3 out of 9 finders are tested. The result is three groups of three finders test for valid QR Code structure. The result is given below in the picture.

Triple QR Codes

QR Code 1
Top left corner
QR Code 2
Top right corner
QR Code 3
Bottom left corner

QR Code Encoder Demo

QR Code Encoder Demo is a test program showing how to encode a QR Code and save it as an image file.

  • Select error correction level.
  • Set module size
  • Set quiet zone
  • Enter the text into the data box. You can use the pipe | character to break the string into segments of numeric, alphanumeric and general text.
  • Press Encode. The QR Code will be displayed.
  • Press Save PNG to save the image in PNG format not using Bitmap.
  • Press Save Image. The Save Image screen will be displayed.

QR Code Encoder Demo

  • Set image file format to your requirements.
  • If all you want is pure QR Code image, press Save and select a file name.
  • The Save QR Code Image screen allows you to save the QR Code image over a brush or image background. You can rotate the QR Code or display it as if it was taken by a camera to yield perspective picture.
  • For testing, you can add circular spots at random over the image.

Save QR Code Image

QR Code Decoder Demo

QR Code Decoder Demo is a test program showing how to scan an image file for QR Codes and convert the decoded data into an array of byte arrays or strings.

QR Code Decoder Demo

  • Click on Load QR Code Image.
  • Select an image file.
  • The image will be displayed.
  • If decoding is successful, the Decoded data area will display the result.
  • If decoding is not successful, the Decoded data area will be blank.
  • If the image contains more than one QR Code, the Decoded data will display the results of all QR Codes.

QR Code Video Decoder

QR Code Video Decoder QRCodeVideoDecoder is a test/demo application that will use the first found web camera in your system. A demo program combining QR Code decoder and video camera image capture. The video camera software is based on the Direct Show Library.

This demo program is using some of the source modules of Camera_Net project published at CodeProject.com and at Github This project is based on DirectShowLib.. Please note the DirectShowLib in this project is a modified subset of the original source modules.

Please note, I have only tested this application on my own video camera. My camera is Logitech HD Webcam C615. I am using frame size of 640 by 480 pixels.

The program sets the camera software to display the video stream in a preview area on the screen. The scanning is 5 frames per seconds. Each frame is captured and tested for a QR Code. Once a QR Code is found, the result is displayed at the Decoded data text box. Decoding stops until the reset button is pressed. If the decoded data is a URI, the Go To URI button is enabled, and you can display this URI on your default web browser.

For video decoding to be successful, each QR Code module must be represented by a few camera pixels. For example, 4 by 4 or more pixels. The QR Code must be reasonably sharp, flat and parallel to the camera. The picture below illustrates the power of the software to transform the image to a square with the finder symbols at their correct positions.

QR Code Video Decoder

History

  • 2018/06/30: Version 1.0 Original version
  • 2018/07/20: Version 1.1.0 DirectShowLib consolidation
  • 2019/05/15: Version 2.0.0 The software was divided into two solutions. Encoder solution and Decoder solution. The encode solution is a multi-target solution. It will produce net462 netstandardapp2.0 libraries.
  • 2019/07/22 Version 2.1.0 ECI Assignment Value support was added.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Uzi Granot
Canada Canada
No Biography provided

Comments and Discussions

 
QuestionQR Code Reader missing the first letter Pin
BrianBroyles14-Jan-20 10:35
MemberBrianBroyles14-Jan-20 10:35 
AnswerRe: QR Code Reader missing the first letter Pin
Uzi Granot14-Jan-20 13:11
mvaUzi Granot14-Jan-20 13:11 
GeneralRe: QR Code Reader missing the first letter Pin
BrianBroyles15-Jan-20 10:10
MemberBrianBroyles15-Jan-20 10:10 
GeneralRe: QR Code Reader missing the first letter Pin
Uzi Granot15-Jan-20 13:26
mvaUzi Granot15-Jan-20 13:26 
QuestionOriginal code Pin
xzamza11-Oct-19 5:41
Memberxzamza11-Oct-19 5:41 
AnswerRe: Original code Pin
Uzi Granot11-Oct-19 6:09
mvaUzi Granot11-Oct-19 6:09 
QuestionCoordinates of the qrcode boxes Pin
Turquoise742-Oct-19 20:38
MemberTurquoise742-Oct-19 20:38 
AnswerRe: Coordinates of the qrcode boxes Pin
Uzi Granot3-Oct-19 3:04
mvaUzi Granot3-Oct-19 3:04 
GeneralRe: Coordinates of the qrcode boxes Pin
Turquoise745-Oct-19 21:22
MemberTurquoise745-Oct-19 21:22 
QuestionSupported QR Code Formats? Pin
db5bnm22-Jul-19 5:58
Memberdb5bnm22-Jul-19 5:58 
AnswerRe: Supported QR Code Formats? Pin
Uzi Granot22-Jul-19 7:39
mvaUzi Granot22-Jul-19 7:39 
AnswerRe: Supported QR Code Formats? Pin
Uzi Granot22-Jul-19 10:27
mvaUzi Granot22-Jul-19 10:27 
AnswerRe: Supported QR Code Formats? Pin
Uzi Granot24-Jul-19 3:42
mvaUzi Granot24-Jul-19 3:42 
GeneralRe: Supported QR Code Formats? Pin
db5bnm24-Jul-19 23:20
Memberdb5bnm24-Jul-19 23:20 
GeneralRe: Supported QR Code Formats? Pin
Uzi Granot25-Jul-19 2:15
mvaUzi Granot25-Jul-19 2:15 
SuggestionOptimization of code Pin
Member 1155713927-Jun-19 7:46
MemberMember 1155713927-Jun-19 7:46 
QuestionHave you considered NuGet / open gitrepo? Pin
Member 1396285525-Jun-19 0:46
MemberMember 1396285525-Jun-19 0:46 
AnswerRe: Have you considered NuGet / open gitrepo? Pin
Uzi Granot25-Jun-19 1:45
mvaUzi Granot25-Jun-19 1:45 
GeneralRe: Have you considered NuGet / open gitrepo? Pin
Member 1396285525-Jun-19 6:01
MemberMember 1396285525-Jun-19 6:01 
QuestionUse the DLL in a Visual Studio 2008 project Pin
ToniTonino25-May-19 1:54
MemberToniTonino25-May-19 1:54 
AnswerRe: Use the DLL in a Visual Studio 2008 project Pin
Uzi Granot25-May-19 3:45
mvaUzi Granot25-May-19 3:45 
PraiseWorks like charm! Pin
Alfred Manoj19-May-19 22:55
MemberAlfred Manoj19-May-19 22:55 
GeneralMy vote of 5 Pin
Anurag Gandhi17-May-19 4:36
professionalAnurag Gandhi17-May-19 4:36 
GeneralRe: My vote of 5 Pin
Uzi Granot17-May-19 4:48
mvaUzi Granot17-May-19 4:48 
QuestionConversion to black and white Pin
Member 1354893020-Feb-19 9:46
MemberMember 1354893020-Feb-19 9:46 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Article
Posted 2 Jul 2018

Stats

113.9K views
20.9K downloads
218 bookmarked