Click here to Skip to main content
13,801,019 members
Click here to Skip to main content
Add your own
alternative version

Stats

27.9K views
5K downloads
133 bookmarked
Posted 2 Jul 2018
Licenced CPOL

QR Code Encoder and Decoder .NET Class Library Written in C# (Ver. 1.1.0)

, 20 Jul 2018
Rate this:
Please Sign up or sign in to vote.
QR Code Encoder and Decoder .NET framework class library is written in C#. The encoder class allows you to create QR Code image from string or byte array. The decoder class allows you to scan a Bitmap image for one or more QR Codes and convert them into array of byte arrays or strings.

QRCodeLibrary Icon

Introduction

The QR Code library allows your program to create (encode) QR Code image and to read (decode) an image containing one or more QR Codes. QRCodeEncoderDecoderLibrary is a .NET framework class library. The source code is written in C#. It is an open source code. The downloads attached to this article include the .NET library and three demo/test applications.

  • QRCodeEncoderDecoderLibrary: A .NET library exposing QR Code encoder and QR Code decoder
  • QRCodeEncoderDemo: A demo program showing how to encode a string or a byte array into a QR Code image file
  • 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 part of the PDF File Writer C# Class Library article.

Version 1.1.0: Direct Show Lib Consolidation

The source code for the direct show library was consolidated into one source module. The unused code was removed. The change is related only to QRCodeVideoDecoder demo/test program. You can delete the DirectShow directory. It is not in use.

Installation

The attached Visual Studio solution source file includes four projects as listed above: 

Integrating QRCodeEncoderDecoderLibrary to your application requires the following steps. Install the attached QRCodeEncoderDecoderLibrary.dll file 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 installed QRCodeEncoderDecoderLibrary.dll. When your application is published, the file QRCodeEncoderDecoderLibrary.dll must be included and installed in the same folder as your executable (.exe) file.

The following "using" statement must be added to all your source files referring to this library:

using QRCodeEncoderDecoderLibrary;

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. Note: The QR Code standard has one more encoding method for Kanji characters. This project does not support this encoding.

  • 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 base class of this project is QRCode. It contains all the basic definitions of the QR Code matrix and common methods for encoding and decoding. The QREncoder is a derived class for converting 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. This object is reusable. If you want to create many QR Codes, just reuse this object. There are no initialization or dispose requirements.

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

Call one of the four Encode methods:

// single text string input
public bool[,] Encode(ErrorCorrection EC, string StringDataSegment);

// multiple text strings input
public bool[,] Encode(ErrorCorrection EC, string[] StringDataSegments);

// single byte array input
public bool[,] Encode(ErrorCorrection EC, byte[] ByteDataSegment);

// multiple byte arrays input
public bool[,] Encode(ErrorCorrection EC, byte[][] ByteDataSegments);

Error correction is an enumeration.

public enum ErrorCorrection
	{
	L, // 7% error correction
	M, // 15% error correction
	Q, // 25% error correction
	H, // 30% error correction
	}

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

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

// the QREncoder converts text string to byte array the class using this conversion
// this method is a member of QRCode the base class of QREncoder
public static byte[] StrToByteArray(string Text)
	{
	// convert string to byte array
	return Text == null ? new byte[0] : Encoding.UTF8.GetBytes(Text);
	}

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

The QRCodeEncoderDecoderLibrary 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 output of the Encode method is a two-dimensional bool array (bool[,]) representing a QR Code image. It is a square array. Black modules are true and white modules are false. The same result can be accessed as QRCodeEncoder.QRCodeMatrix. The matrix dimension is given in QRCodeEncoder.QRCodeDimension.

The next logical step is to convert the bool array into a QR Code Bitmap image file. Class QRCodeToBitmap has a few methods to achieve that. The example below shows how to create QR Code image file with the content "QR Code Library Project".

// create reusable QREncoder object
QREncoder QRCodeEncoder = new QREncoder()

// encode input text string using error correction M
QRCodeEncoder.Encode(ErrorCorrection.M, "QR Code Library Project");

// create bitmap image
// each module will be 4 by 4 pixels
// the quiet zone around the QR Code will be 8 pixels
Bitmap QRCodeImage = QRCodeToBitmap.CreateBitmap(QRCodeEncoder, 4, 8);

// save image to a disk file
FileStream FS = new FileStream(FileName, FileMode.Create);
QRCodeImage.Save(FS, ImageFormat.Png);
FS.Close();

The QRCodeToBitmap has three more methods to convert QR Code bool[,] matrix to Bitmap image. These methods display the QR Code image over a background. In addition, the image can be rotated, or distorted by perspective projection. These methods were created to test the decoding capabilities of this library. The calling sequence of one of them is shown below:

/// <summary>
/// Create Bitmap image from QR code array over given solid or hatch background
/// </summary>
/// <param name="QRCode" />QR Code<param></param>
/// <param name="ModuleSize" />Module size in pixels<param></param>
/// <param name="QuietZone" />Quiet zone in pixels<param></param>
/// <param name="Background" />SolidBrush or HatchBrush background<param></param>
/// <param name="ImageWidth" />Output image width<param></param>
/// <param name="ImageHeight" />Output image height<param></param>
/// <param name="QRCodeCenterPosX" />QR code center X position<param></param>
/// <param name="QRCodeCenterPosY" />QR code center Y position<param></param>
/// <param name="Rotation" />QR code rotation in degrees<param></param>
/// <returns>Bitmap image of QR code</returns>
public static Bitmap CreateBitmap
    (
    QRCode QRCode,
    int ModuleSize,
    int QuietZone,
    Brush Background,
    int ImageWidth,
    int ImageHeight,
    double QRCodeCenterPosX,
    double QRCodeCenterPosY,
    double Rotation
    )

QR Code Decoding

The QRDecoder is a derived class of QRCode for converting QR Code Bitmap images into an array of byte arrays. 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 requirements.

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

Call ImageDecoder method.

// decode image
// QRCodeInputImage is a Bitmap
byte[][] DataByteArray = QRCodeDecoder.ImageDecoder(QRCodeInputImage);

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:

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
// this method is a member of QRCode the base class of QRDecoder
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.
  • 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 Image. The Save Image screen will be displayed.

QR Code Encoder Demo

  • Set quiet zone width in pixels to your requirements.
  • Set module width in pixels to your requirements.
  • 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

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

You may also be interested in...

Pro
Pro

Comments and Discussions

 
GeneralMy vote of 5 Pin
Member 1290943921-Aug-18 6:52
memberMember 1290943921-Aug-18 6:52 
QuestionCompile the source code Pin
forumarbeit23-Jul-18 11:07
memberforumarbeit23-Jul-18 11:07 
AnswerRe: Compile the source code Pin
Uzi Granot23-Jul-18 11:26
memberUzi Granot23-Jul-18 11:26 
GeneralRe: Compile the source code Pin
forumarbeit12-Aug-18 11:55
memberforumarbeit12-Aug-18 11:55 
GeneralRe: Compile the source code Pin
Uzi Granot13-Aug-18 4:00
memberUzi Granot13-Aug-18 4:00 
GeneralRe: Compile the source code Pin
forumarbeit14-Aug-18 1:42
memberforumarbeit14-Aug-18 1:42 
GeneralRe: Compile the source code Pin
Uzi Granot14-Aug-18 3:36
memberUzi Granot14-Aug-18 3:36 
GeneralRe: Compile the source code Pin
forumarbeit14-Aug-18 7:58
memberforumarbeit14-Aug-18 7:58 
Questionhow can I call it on a SSRS report ? Pin
Member 1319453012-Jul-18 19:28
memberMember 1319453012-Jul-18 19:28 
AnswerRe: how can I call it on a SSRS report ? Pin
Uzi Granot13-Jul-18 2:18
memberUzi Granot13-Jul-18 2:18 
AnswerRe: how can I call it on a SSRS report ? Pin
O.Puchuu2-Aug-18 3:26
memberO.Puchuu2-Aug-18 3:26 
PraiseNice stuff, I might find a way to use it... Pin
James Hunter Ross3-Jul-18 15:11
memberJames Hunter Ross3-Jul-18 15:11 

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.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web05 | 2.8.181215.1 | Last Updated 20 Jul 2018
Article Copyright 2018 by Uzi Granot
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid