Explanation of the free and open-source DotNet QR code operation component ThoughtWorks. QRCode (. NET Component Introduction 4) and thoughtworks. qrcode

Source: Internet
Author: User
Tags reflector

Explanation of the free and open-source DotNet QR code operation component ThoughtWorks. QRCode (. NET Component Introduction 4) and thoughtworks. qrcode

In our life, there is something that is almost about to become another electronic "ID card", that is, the QR code. No matter in the process of software development or in the daily life of common users, the QR code is almost inseparable. A QR code (dimen1_barcode), also known as a two-dimensional bar code, is a readable Bar Code expanded on the basis of a one-dimensional bar code. The device scans two-dimensional barcode and identifies the binary data recorded in the length and width of the barcode to obtain the information contained in it. Compared with the one-dimensional barcode, the QR code records more complex data, such as slices and network links.

Today, we will introduce a free and open-source QR code operation component. The ThoughtWorks. QRCode component can efficiently and stably generate the QR code we need. Next, let's take a look at this component.

1. Overview of ThoughtWorks. QRCode components:

The QRCode library is a. NET component that can be used to encode and decode QRCode. QRCode is a two-dimensional Barcode originating from Japan. Nowadays, it is widely used in a wide range of industrial fields. Used for tracking and inventory management of vehicle parts. QR represents "Quick Response ". It was created in 1994 by the Japanese company Denso-Wave to decode content at high speed. Today, QR codes are used on mobile phones to ease data input. QRCode can also be printed on a business card or displayed on any monitor, and then captured by a mobile phone, as long as the mobile phone has software to read QRCode. The QRCode Library provides the following functions: encode the content into a QR code image, which can be saved as JPEG, GIF, PNG, or bitmap formats, and decode the QR code image.

This library can be used for any. NET 2.0 Windows application, ASP. NET Web application, or Windows Mobile device application. The following is the declaration of this component. "This article and any relevant source code and files have been licensed by the Code project open license (CPOL)."

Ii. Analysis of core objects and methods related to ThoughtWorks. QRCode:

The main classes related to ThoughtWorks. QRCode are as follows:

The above uses. NET Reflector to decompile the DLL file to view the source code. Because I only downloaded the DLL file and didn't download the source code, I directly used. NET Reflector to view the source code. Next I will introduce some components and methods:

1. QRCodeEncoder: QR code class.

 public enum ENCODE_MODE{ ALPHA_NUMERIC, NUMERIC, BYTE}public enum ERROR_CORRECTION{ L, M, Q, H}public virtual Bitmap Encode(string content, Encoding encoding){ bool[][] flagArray = this.calQrcode(encoding.GetBytes(content)); SolidBrush brush = new SolidBrush(this.qrCodeBackgroundColor); Bitmap image = new Bitmap((flagArray.Length * this.qrCodeScale) + 1, (flagArray.Length * this.qrCodeScale) + 1); Graphics graphics = Graphics.FromImage(image); graphics.FillRectangle(brush, new Rectangle(0, 0, image.Width, image.Height)); brush.Color = this.qrCodeForegroundColor; for (int i = 0; i < flagArray.Length; i++) {  for (int j = 0; j < flagArray.Length; j++)  {   if (flagArray[j][i])   {    graphics.FillRectangle(brush, j * this.qrCodeScale, i * this.qrCodeScale, this.qrCodeScale, this.qrCodeScale);   }  } } return image;}

2. QRCodeDecoder: QR code decoding class.

 public virtual string decode(QRCodeImage qrCodeImage, Encoding encoding){ sbyte[] src = this.decodeBytes(qrCodeImage); byte[] dst = new byte[src.Length]; Buffer.BlockCopy(src, 0, dst, 0, dst.Length); return encoding.GetString(dst);} public virtual sbyte[] decodeBytes(QRCodeImage qrCodeImage){ DecodeResult result; Point[] adjustPoints = this.AdjustPoints; ArrayList list = ArrayList.Synchronized(new ArrayList(10)); while (this.numTryDecode < adjustPoints.Length) {  try  {   result = this.decode(qrCodeImage, adjustPoints[this.numTryDecode]);   if (result.CorrectionSucceeded)   {    return result.DecodedBytes;   }   list.Add(result);   canvas.println("Decoding succeeded but could not correct");   canvas.println("all errors. Retrying..");  }  catch (DecodingFailedException exception)  {   if (exception.Message.IndexOf("Finder Pattern") >= 0)   {    throw exception;   }  }  finally  {   this.numTryDecode++;  } } if (list.Count == 0) {  throw new DecodingFailedException("Give up decoding"); } int num = -1; int numErrors = 0x7fffffff; for (int i = 0; i < list.Count; i++) {  result = (DecodeResult) list[i];  if (result.NumErrors < numErrors)  {   numErrors = result.NumErrors;   num = i;  } } canvas.println("All trials need for correct error"); canvas.println("Reporting #" + num + " that,"); canvas.println("corrected minimum errors (" + numErrors + ")"); canvas.println("Decoding finished."); return ((DecodeResult) list[num]).DecodedBytes;}

3. QRCodeBitmapImage: bitmap image.

 public class QRCodeBitmapImage : QRCodeImage{ // Fields private Bitmap image; // Methods public QRCodeBitmapImage(Bitmap image); public virtual int getPixel(int x, int y); // Properties public virtual int Height { get; } public virtual int Width { get; }}
public interface QRCodeImage{ // Methods int getPixel(int x, int y); // Properties int Height { get; } int Width { get; }}

The above is an introduction to some methods of the ThoughtWorks. QRCode component. If you need to learn more, you can view the corresponding source code.

3. ThoughtWorks. QRCode QR code operation example:

1. Generate a QR code (the QR code is not set ).

/// <Summary> /// generate a QR code /// </summary> /// <param name = "content"> string containing the generated QR code </param> // /<param name = "path"> path </param> // <returns> </returns> public static string CreatehoughtWorksQrCode (string content, string path) {if (string. isNullOrEmpty (content) {throw new ArgumentNullException (content);} if (string. isNullOrEmpty (path) {throw new ArgumentNullException (path);} var qrCodeEncoder = new QRC OdeEncoder {QRCodeEncodeMode = QRCodeEncoder. ENCODE_MODE.BYTE, QRCodeScale = 4, QRCodeVersion = 8, QRCodeErrorCorrect = QRCodeEncoder. ERROR_CORRECTION.M}; Image image = qrCodeEncoder. encode (content); var filename = DateTime. now. toString ("yyyymmddhhmmssfff") + ". jpg "; var filepath = string. format ("{0} {1}", path, filename); FileStream fs = null; try {fs = new FileStream (filepath, FileMode. openOrC Reate, FileAccess. write); image. save (fs, System. drawing. imaging. imageFormat. jpeg);} catch (IOException ex) {throw new IOException (ex. message);} finally {if (fs! = Null) fs. Close (); image. Dispose ();} return CodeDecoder (filepath );}

2. Select the type of the generated QR code.

/// <Summary> /// select the type of the QR code to be generated /// <param name = "strData"> the text or number to be generated. Chinese characters are supported. For example, "4408810820 Shenzhen-Guangzhou" Or: 4444444444 </param> // <param name = "qrEncoding"> three dimensions: BYTE, ALPHA_NUMERIC, NUMERIC </param> /// <param name = "level"> size: l m q h </param> /// <param name = "version"> version: for example, 8 </param> /// <param name = "scale"> ratio: for example, 4 </param> /// <returns> </returns> /// </summary> public void CreateCode_Choose (string strData, string qrEncoding, string level, int version, int scale) {if (string. isNullOrE Mpty (strData) {throw new ArgumentNullException (strData);} if (string. isNullOrEmpty (qrEncoding) {throw new ArgumentNullException (qrEncoding);} if (string. isNullOrEmpty (level) {throw new encode (level);} var qrCodeEncoder = new QRCodeEncoder (); var encoding = qrEncoding; switch (encoding) {case "Byte": qrCodeEncoder. QRCodeEncodeMode = QRCodeEncoder. ENCODE_MODE.BYTE; break; ca Se "AlphaNumeric": qrCodeEncoder. QRCodeEncodeMode = QRCodeEncoder. ENCODE_MODE.ALPHA_NUMERIC; break; case "Numeric": qrCodeEncoder. QRCodeEncodeMode = QRCodeEncoder. ENCODE_MODE.NUMERIC; break; default: qrCodeEncoder. QRCodeEncodeMode = QRCodeEncoder. ENCODE_MODE.BYTE; break;} qrCodeEncoder. QRCodeScale = scale; qrCodeEncoder. QRCodeVersion = version; switch (level) {case "L": qrCodeEncoder. QRCodeError Correct = QRCodeEncoder. ERROR_CORRECTION.L; break; case "M": qrCodeEncoder. QRCodeErrorCorrect = QRCodeEncoder. ERROR_CORRECTION.M; break; case "Q": qrCodeEncoder. QRCodeErrorCorrect = QRCodeEncoder. ERROR_CORRECTION.Q; break; default: qrCodeEncoder. QRCodeErrorCorrect = QRCodeEncoder. ERROR_CORRECTION.H; break;} Image image = null; FileStream fs = null; try {// text Generation image = qrCodeEncoder. encode (strD Ata); var filename = DateTime. Now. ToString ("yyyymmddhhmmssfff") + ". jpg"; var filepath = HttpContext. Current. Server. MapPath (@"~ \ Upload ") +" \ "+ filename; fs = new FileStream (filepath, FileMode. openOrCreate, FileAccess. write); image. save (fs, System. drawing. imaging. imageFormat. jpeg);} catch (IOException ioex) {throw new IOException (ioex. message);} catch (Exception ex) {throw new Exception (ex. message);} finally {if (fs! = Null) fs. Close (); if (image! = Null) image. Dispose ();}}

3. QR code decoding.

/// <Summary> /// QR code decoding /// </summary> /// <param name = "filePath"> image path </param> /// <returns> </returns> public static string CodeDecoder (string filePath) {if (string. isNullOrEmpty (filePath) {throw new ArgumentNullException (filePath);} try {if (! File. exists (filePath) return null; var myBitmap = new Bitmap (Image. fromFile (filePath); var decoder = new QRCodeDecoder (); var decodedString = decoder. decode (new QRCodeBitmapImage (myBitmap); return decodedString;} catch (Exception ex) {throw new Exception (ex. message );}}

Iv. Summary:

Like the previous introduction of components, the first is the component overview, the core class of the component, and the usage of the component. It took a lot of time to find and modify the component overview, I don't know why, this component does not find relevant materials, or even the author is replaced by a certain person, but the Internet is like this and we don't need to know who made it, it is easy to use. In the component and js plug-in for generating QR codes, I personally like this component and feel very good. All components and methods have personal preferences and use environments, you can choose one based on your needs.

As developers provide a demo, they can directly go to the above link to view the download. Here we will not provide an example.

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.