QRCoder – an Open Source QR code generator implementation in C#

QRCoder demoIn modern times QR codes should be known by pretty much everyone. Since smartphones are becoming increasingly popular, QR codes can also be found at more and more places in our everyday lives. As a fairly serious geek this should be reason enough to engage a bit more in detail with the technology behind it. And what way seems to be more suitable than implementing a QR code generator by yourself?

Because C# is my favourite programming language, the choice fell accordingly to this language. Sadly information on the QR code are not so easy to get. The easiest way of course would be the official way – simply buy the ISO/IEC document. That would be the ISO/IEC 18004. But there’s also a crux on that. The ISO 18004 costs round about 232$, which is a little too expensive for a non-profit hobby project, however.

How does QR codes work (technically)?

Luckily, there are some really good sources on the internet, that explain the functional principles of a QR code generator. With the help of these sites, I got down to my own implementation. For those who want to read up on the technical side of the subject, I listed below my main sources for you:

Since the complete logic behind the QR code generation process is way more complicated and beyond the scope of this post, I will not explain this further here. You might want to read up on the pages linked above and if you have any questions, of course, you can write me a comment. I’ll then give my best to answer your questions.

Need help with implementation? Are you looking for an individual solution? Do you need dotted, transparent or specially designed QR codes? Then feel free to contact me.

I have already implemented several QR code solutions for customers in various industries. So why not for you?

In the following I like to show you how to use my library and under what license it is published.

From where can I get QRCoder?

You can get the source code of QRCoder, that’s how I called my QR code generator, on GitHub. The code is licensed under the MIT license, so that QRCoder can be used in non-commercial as well as commercial projects.

github logo
QRCoder @ Github

Nevertheless, if you use the library for one of your projects, I would be happy if you would leave a short comment. (It’s always nice to see what will become of his “code babies”.)

How to use QRCoder?

The usage of QRCoder is relatively simple. At first you must (of course) add a reference to the QRCoder.dll. To create a QR code and display it you need only 4 more lines of code.

private void renderQRCode()
{
   QRCodeGenerator qrGenerator = new QRCodeGenerator();
   QRCodeData qrCodeData = qrGenerator.CreateQrCode("The text which should be encoded.",      QRCodeGenerator.ECCLevel.Q);
   QRCode qrCode = new QRCode(qrCodeData);
   Bitmap qrCodeImage = qrCode.GetGraphic(20);
}

In the first line the QR code generator is instantiated, in the second line a QR code data object is created, in the third line the QR code object is created and in the fourth line, the QR code is rendered as a bitmap and displayed in a PictureBox. That’s it! There is nothing more to do, to create a QR code and show it.

The appropriate error correction level

The CreateQrCode() function takes two arguments. At first the string which shall be encoded in the QR code and as second argument the error correction level (ECCLevel). Here, the levels L (7%), M (15%), Q (25%) and H (30%) are available, whereby the percentage indicates how much of the QR-code can be hidden/destroyed until the error correction algorithm can’t recreate the original message which was encoded in the QR code.

Be creative – render the QR code your way!

As shown above, a QR code can be rendered as Bitmap by using the GetGraphic() function. When using this function a classic layouted, black and white QR code graphic is generated. If you are a fan of colorful and fancy graphics, you may want to render your QR code in a more beatiful way than the given solution by using the GetGraphic() function.

No problem! Therefore I added the ModuleMatrix property which gives you a list of BitArrays (which are representing logical lines). So, for example, if in list index 3 (line 2) on BitArray index 4 (column 3) the bool value is true, then you have to render this block element as dark element. If the value is false, it has to be rendered as light element.

Now, by iterating through the List<BitArray> ModuleMatrix, you can implement your on function to render the QR code.

//List<System.Collections.BitArray>ModuleMatrix

foreach (System.Collections.BitArray line in qrCode.ModuleMatrix)
{
    foreach (bool block in line)
    {
        //Write your own rendering algorithm here
        //When block==true then render dark, else render light
    }
}

Feedback and feature plans

If you have (constructive) feedback, ideas, questions, tips or problems with the library, then just write me a comment. Also everytime somebody of you forks this project on GitHub I’ll be really happy.

Because I’m running a little bit out of time at the moment, I’m not able to give something like a clear and precise roadmap. Nevertheless there are some ideas I really like to implement in the future. For example some more custom rendering algorithms/functions. Also I can imagine some more functions to create QR codes for special purposes, like a function which takes WiFi credentials and renders them as QR code. Or a function which takes mobile numbers or vcard.vcf files and renders them or … This thing now exists. Try the PayloadGenerator class and generate your favourite payload.

But for all that I need time. So if you are motivated, talented and want to bring this QR code library to the top, fork it on Github and work together with me.

So far, so good. I hope you enjoyed reading this article and wish you a lot of fun with the QRCoder library!

49 Comments

  1. Sagar Saradesays:

    Hi,
    Amazing code really appreciate , I easily used it but unfortunately it behaves unexpectedly. I am trying to generate QR which includes ULR with some query string parameters. It works perfectly but sometimes it writes wrongly.
    e.g https://something.com?para1=hAf83Afg&para=225478
    which encoded as
    1. htt’s://something.com?para1=hAf83Afg&para=225478 or https://something.com?para1=hAf83Af(&para=225478

    Please suggest if I am doing something wrong. Thanks in advance!!!

    QRCodeGenerator qrGenerator = new QRCodeGenerator();
    QRCodeGenerator.QRCode qrCode = qrGenerator.CreateQrCode(Code, QRCodeGenerator.ECCLevel.Q);
    System.Web.UI.WebControls.Image imgBarCode = new System.Web.UI.WebControls.Image();
    imgBarCode.Height = 110;
    imgBarCode.Width = 110;
    using (Bitmap bitMap = qrCode.GetGraphic(20))
    {
    using (MemoryStream ms = new MemoryStream())
    {
    bitMap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
    byte[] byteImage = ms.ToArray();

    buffer = byteImage;
    imgBarCode.ImageUrl = “data:image/png;base64,” + Convert.ToBase64String(byteImage);
    }
    plBarCode.Controls.Add(imgBarCode);
    }

    • Hello Sagar,

      your code looks correct. Unfortunately I can’t reproduce your problem. When I encode your input string, I get an QR code which works without problems. Which version of the QRCoder.dll do you use? This sound like a bug we had some versions ago. But this is fixed. With the current version I also couldn’t reproduce this error. So please try to update to the newest QrCoder release. (It’s version 1.2.6 – https://www.nuget.org/packages/QRCoder/)

      If you already use the newest QrCoder version and still get the error, please tell me which QrCode reader you use.

      Kind regards,
      Raffael

  2. TEY JIN RONGsays:

    I encounter a problem on the QR Code output different in error correction Level Q(25%) with another Level of error correction

    Example: I input ‘26684C94’ QR Code become ‘266G4C94’ in error correction Level Q(25%)

    • Hello Tey Jin,

      which version of the QRCoder do you use? This sound like a bug we had some versions ago. But this is fixed. With the current version I also couldn’t reproduce this error. So please try to update to the newest QrCoder release.

  3. Louissays:

    Can you help to explain how can i export SVG format string into HTML page?
    I successfully create a SVG String and send to client. But i dont know how to display it or download that SVG.
    Thanks for any help.

  4. saqibsays:

    This is the best library if you are programming in .net and wants to generate QR code with small length. In my case I need to pass 1000 length of numeric data. Can you please help me how to do it with your library? Wikipedia says QR code can have 1000+ length of numeric data.

    • Hi saqib,

      what exactly doesn’t work or better said, where do you need help. To encode 1000 digits, just pass them to the QRCoder and it will encode them. (The QRCoder will recognize, that your input just consists of digits and therefore choose the numeric mode.)

  5. Andrew Stockssays:

    Hi, I just tried your QRCoder using NuGet …
    I like it as it is very simple and useful.

    Please could you advise – does it do the reverse operation –
    When I have created a QR image using this, can I take that image
    I have just generated and get the text back out?

    If not, when would you plan on having this feature?

    Thanks

  6. Leonelsays:

    Gracias, desde Argentina por hacernos la vida más fácil.

  7. Justinsays:

    Great job on this project. It’s by far the easiest way to generate QR codes. I do have a need that I’m not sure this library meets. I’d like to take the base64 encoded string and parse out the value of the QR code. For example, if a QR code was generated to redirect to http://google.com, then I want to take the base64 encoded string, run in through a function and have it return http://google.com. What do you think?

  8. Nitin VARMA Manthenasays:

    Nice post! thank you

  9. P Silvasays:

    Hello, I was able to successfully create QRCodes using your library, but apparently it adds the string “http://” to every string I use.
    If I type “my coded message” the scan result is “http://my coded message”
    What am I doing wrong?

    • Sounds like you are using the “PayloadGenerator”. If you want “freestyle” text, just stop using the PayloadGenerator class and pass your text directly as payload.

      But to be more precise, I have to see your exact coding. So please show the lines, where you call the QRCoder classes/functions.

  10. Cnrbrssays:

    Thank you for this great job.
    Do you have any ideas why I can’t add a reference to this library in Microsoft access 2013?

  11. misoasays:

    Nice library. Thank you for sharing.

    Can you tell me the maximum number of characters (UTF8) it can encode??
    Interest in japanese kanji letters. I believe they take 3bytes each
    I’ve found that standard offers a max of 3Kbytes, with lowest error correction, without logo image

  12. Edenilsonsays:

    How adjust the size that is created?

    • Just change the first parameter of the GetGraphics-method. It’s the pixelsPerBlock-size. It sets the amount of pixels each black and white block will get.

      For example: Bitmap qrCodeImage = qrCode.GetGraphic(10);

  13. Carlos Msays:

    I’ve downloaded your .zip file, but I could not find the QRCoder.dll. Can you help me with this please?

    Regards

    • Cnrbrssays:

      I guess this can help. But also I don´t have any idea of that I´m doing xD.
      http://www.geeksengine.com/article/create-dll.html

      • Nice article, but not the answer…Your article explains how to generate a DLL with COM object for wrapping it in VBA.

        Concerning Carlos’ question – just open the C# project (from the zip file) in Visual Studio and click on run/debug/compile. After a few seconds the DLL file will be generated. Then you can reference this DLL file in your major project.

        • Cnrbrssays:

          Thank you for getting the time :3. I´m totally new on programming. So I try everything I can get.

  14. Kirk De Villierssays:

    Hi

    Can you help me out. Trying to generate qr codes for the medical industry. I need to consistently generate qr codes which are 6cm by 6cm. Is this possible with your API.

    • Yes it is possible. My library produces a Bitmap object. The size of the print is your part. If you print the Bitmap in 6x6cm 12x12cm or 15x120cm is your choice. (Or better said: It depends on your printing / Bitmap.save() implementation.)

      If you need futher assistance, you may write me an email. I do also offer consulting and programming. ;-)

  15. twooclocksays:

    Hi!
    Is it possible to get rid of the white edge surrounding the bitmap?
    I’m using .GetGraphic(20) method and than saving into jpeg file.
    It seems like saved jpeg file has 16px white edge around qrcode…?
    Thank you!

    • The white space around the QRCode is defined in the QR specification. That’s the reason I implemented it. Nevertheless, if you want to drop it, use the “ModuleMatrix”-Array from the QRCode object. It contains the info, which points has to become white and which black. With this information an .NET’s Graphics-classes you can implement your own visualisation routine.

  16. Mariussays:

    Looked nice, but even the sample code do not work :(.

    I use:

    QRCodeGenerator qrGenerator = new QRCodeGenerator();
    QRCodeGenerator.QRCode qrCode = qrGenerator.CreateQrCode(“MyTex”,QRCodeGenerator.ECCLevel.Q);
    System.Drawing.Image b = qrCode.GetGraphic(20);

    And get the Error “The type name ‘QRCode’ does not exist in the type ‘QRCoder.QRCodeGenerator’

    • The error comes from changed sources on GitHub. Unfortunately I haven’t updated the example code. Sorry, I’ll do that in near future.

      • potashisays:

        So, whats the updated sample code? Can u plz update it asap. I really need it

  17. Joshsays:

    Any guide / help on how to use it in a webforms asp.net (c#) app? pictureBoxQRCode.BackgroundImage = qrCode.GetGraphic(20); doesn’t work as you don’t have access to a picture box.

  18. How can i add 2 or more fields to encode into Qr code from one form to another ?Pls help me out.

  19. sorensays:

    It works perfect.
    awesome.
    do you have any plan to put it on NuGet?
    I can help, if you want.
    (sorry for bad English).

  20. S.mohanarangansays:

    Hello,

    QRCoder.dll After add Reference
    error in aspx page, Could not load file or assembly ‘QRCoder’ or one of its dependencies. This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded.
    I Down Load the File From aspsnippets.com Dynamically generate and display QR code Image in ASP.Net. I got this error, Help Me.

    Thanks In advance

    • Hello S.mohanarangan,

      this sounds like you’re using an older version of the .NET framework. The QRCoder library is compiled against .NET 4.0. If you’re using an older version (maybe 3.5, 3.0, etc.) for your webproject you have two possibilities:

      1) Download the QRCoder sourcecode from GitHub. Open the QRCoder project in Visual Studio. Change the target framework from 4 to 3.5 and compile it. The use the fresh compiled DLL in your webproject.

      2) Switch the target framework of your webproject to .NET 4.0 or higher.

  21. Nayefsays:

    Can it work in ASP.NET application?

  22. Brunosays:

    I can’t get it to work in VB on an aspx page.

    This is what I’ve got, and it renders some crazy characters on the screen. Can’t anybody help me out with a working VB example for an aspx website?

    Dim qrGenerator As New QRCoder.QRCodeGenerator()
    Dim qrCode As QRCoder.QRCodeGenerator.QRCode = qrGenerator.CreateQrCode(“Test me”, QRCoder.QRCodeGenerator.ECCLevel.H)
    qrCode.GetGraphic(20).Save(Response.OutputStream, ImageFormat.gif)
    qrCode.GetGraphic(20).Dispose()

  23. saqisays:

    why i am getting white background picturbox ?

  24. Faruquesays:

    I think I have found a bug, if you encode
    https://play.google.com/store/apps/details?id=com.good.android.gfe
    ECCLevel.Q
    Format Jpeg
    the QR decodes to
    https://play.google.com/store/apps/details?id=com.wood.android.gfe
    Am I doing something wrong?

  25. This is amazing. I need to generate QR Codes as Textures in Unity3d, and I was able to use this great encoder and create a texture2d asset rather than a bitmap. Many thanks for the awesome library!

    • Samsays:

      I would do the same thing but I have lots of errors when I import the script. What is your approach?

  26. Pierresays:

    Good day,

    I have been trying to use this code, but at one instance, the one character does not read back correctly. Instead of a ‘9’ it places a ‘)’ . This is the 132nd character in the string. And then the rest of the string is correct.

    Here is the test string:
    le32VAUZlblUPU7YZYsLX2JzegYoU+Om7rXsGIJlQXi5CPHldOguUa4d/SL/u2R2rh39Iv+7ZHauHf0i/7tkdl8GG4ELgJcOvv7hBVjKQgy+/uEFWMpCDEP+SUdD3coyrh3)Iv+7ZHauHf0i/7tkdq4d/SL/u2R2xLHN7QAVoO2uHf0i/7tkdq4d/SL/u2R2rh39Iv+7ZHasq7L++xeT/Wp1upQSjVpj8gzb8g30yUQ=

    Appreciate what you have done so far
    Thank you in advance

    • Pierresays:

      Don’t worry, I am now using another library. Thanks anyways

  27. AV Awesomesays:

    Will You Please Suggest me how to create qr code of business card

  28. O'Briansays:

    Very nice project. Easy to use.

    A QR decoder would be nice :-)

Leave a comment

Please be polite. We appreciate that. Your email address will not be published and required fields are marked