Free Open-source DotNet QR code operation component ThoughtWorks. QRCode (. NET Component Introduction 4), thoughtworks. qrcode

Source: Internet
Author: User

Free Open-source DotNet QR code operation component ThoughtWorks. QRCode (. NET Component Introduction 4), 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 know more methods, you can check the corresponding source code.

Three. ThoughtWorks.QRCode QR code operation example: 1. Generate QR code (the QR code is not set)
        /// <summary>
        /// Generate QR code
        /// </ summary>
        /// <param name = "content"> String with 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 QRCodeEncoder
            {
                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.OpenOrCreate, 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 relevant type for generating the QR code.
        /// <summary>
        ///Select the relevant type of QR code generation
        /// <param name = "strData"> The text or number to be generated supports Chinese. For example: "4408810820 Shenzhen-Guangzhou" Or: 4444444444 </ param>
        /// <param name = "qrEncoding"> Three sizes: BYTE, ALPHA_NUMERIC, NUMERIC </ param>
        /// <param name = "level"> Size: L M Q H </ param>
        /// <param name = "version"> version: like 8 </ param>
        /// <param name = "scale"> Scale: like 4 </ param>
        /// <returns> </ returns>
        /// </ summary>
        public void CreateCode_Choose (string strData, string qrEncoding, string level, int version, int scale)
        {
            if (string.IsNullOrEmpty (strData))
            {
                throw new ArgumentNullException (strData);
            }
            if (string.IsNullOrEmpty (qrEncoding))
            {
                throw new ArgumentNullException (qrEncoding);
            }
            if (string.IsNullOrEmpty (level))
            {
                throw new ArgumentNullException (level);
            }
            var qrCodeEncoder = new QRCodeEncoder ();
            var encoding = qrEncoding;
            switch (encoding)
            {
                case "Byte":
                    qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;
                    break;
                case "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.QRCodeErrorCorrect = 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 to generate pictures
                image = qrCodeEncoder.Encode (strData);
                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. Two-dimensional code decoding.
        /// <summary>
        /// QR code decoding
        /// </ summary>
        /// <param name = "filePath"> picture 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);
            }
        }
4. Summary:
    Like the previous introduction of components, the first is the overview of the component, the core classes of the component, and the method of using the component. It took a lot of time to find the relevant overview of the component in this component. I do n’t know why, this component does not Find the relevant information, even the author is replaced by XYZ, and finally find some introductions here: https://www.codeproject.com/articles/20574/open-source-qrcode-library. But this is the case with the Internet. We don't need to know who made it, as long as it's convenient to use. Among the components and js plug-ins that generate QR codes, I personally like this component. I feel very good. Any component or method has a personal preference and usage environment. Readers can choose according to their own circumstances.

   Since the developer provides a demo, you can directly go to the link above to view the download, and I will not do an example here.

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.