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!

77 Comments

  1. Joaosays:

    Im trying to generate a qr code with this text: 100;FLOW;4579301;200

    I’m getting only the last part 4579301;200

  2. Nassersays:

    I am using QRCoder C# library with DLL version 1.3.7, when printing the QR code the QR image is printed without the position finder squares (inner eye) as shown in the below screenshot so the QR will not be readable knowing that if I placed the squares with image editor (i.e. MS Paint) the QR code can be easily recognized
    I am using the following code
    QRCodeGenerator qrGenerator = new QRCodeGenerator();
    QRCodeGenerator.ECCLevel eccLevel = (QRCodeGenerator.ECCLevel)0;
    qrCodeData = qrGenerator.CreateQrCode(txt, eccLevel);
    QRCode qrCode = new QRCode(qrCodeData);
    QRImage = qrCode.GetGraphic(20, Color.Black, Color.White, null, 100);

  3. sai kolimisays:

    Hi,

    I am using QRcoder since couple of years to insert QRcode images in worddocument.

    However, recently I am receivng this System.Runtime.InteropServices.ExternalException: ‘A generic error occurred in GDI+.’.
    Below is the code i’m using. Can someone please help me on this to resolve.

    var qrGenerator = new QRCodeGenerator();
    var qrCodeData = qrGenerator.CreateQrCode(text, QRCodeGenerator.ECCLevel.Q);
    var qrCode = new QRCode(qrCodeData);
    var qrCodeImage = qrCode.GetGraphic(20);
    qrCodeImage.Save(ConfigurationManager.AppSettings[“QRImageDirectory”] + @”\qrcode.bmp”);
    return ConfigurationManager.AppSettings[“QRImageDirectory”] + @”\qrcode.bmp”;
    }

  4. shostakovichsays:

    Thanks and best regards

  5. Bouquetsays:

    Hello
    Have you sample code for use with VBA
    The library QRCoder allredy install
    Thanks and best regards
    Tony

  6. rosdisays:

    This is an awesome package… it is so easy to use, and full-featured! It targets .NET Standard 2 so I can use it in both legacy and .NET Core Apps!.. so cool!.. couldn’t be more happier!

  7. Tonysays:

    I have an odd intermittent issue with QRCoder version 1.3.5 that I got from Package Manager.

    When I pass strings to CreateQrCode i get data encoded in the QR Code that I did not send. For instance I pass in 6J0001290251905249000835482:ZD but when the QR Code is scanned it is decoded as 6J0001290251905249000835482:ZF
    Now that being said if I change the version from 2 to 3 it encodes correctly. This came about because I have a constraint that I am required to use Version 2 with ECC Q.

    I use the following code:
    QRCodeGenerator qrGenerator = new QRCodeGenerator();
    QRCodeData qrCodeData = qrGenerator.CreateQrCode(“6J0001290251905249000835482:ZD”, QRCodeGenerator.ECCLevel.Q,false,false,QRCodeGenerator.EciMode.Default,2);
    QRCode qrCode = new QRCode(qrCodeData);
    Bitmap qrCodeImage = qrCode.GetGraphic(23);

    All help is greatly appreciated.

    Regards,
    Tony

  8. Hi
    I am trying to come up with a 2D Complex Mail Data Mark barcode (see https://www.dlsoft.com/barcode_types/mailmark.htm).
    Can I use this library? I cannot see what options I should set for this barcode type.
    Regards
    Terence

  9. kamibrahimsays:

    I can’t able to read the both the side using mobile like Horizontally and Vertically

  10. kamibrahimsays:

    I can’t able to read the both the side using mobile.

  11. Thanks for your library its very helpful!
    But how can I resize the QR to be fit in my picture box? Sometimes it’s too big, sometimes too small.

  12. sathishsays:

    need QR Decoder C# code

  13. jodi319says:

    I have successfully used QRCoder for vCard, WiFi and URL. With WiFi, is it at all possible to check if the connection has been established and then open default browser and go to specific URL?

  14. Johnsays:

    I am getting an error on some servers when trying to convert the code to a B64 string. Here is the trace:

    “InnerException”: {

    “Message”: “An error has occurred.”,

    “ExceptionMessage”: “A generic error occurred in GDI+.”,

    “ExceptionType”: “System.Runtime.InteropServices.ExternalException”,

    “StackTrace”: ” at System.Drawing.Image.Save(Stream stream, ImageCodecInfo encoder, EncoderParameters encoderParams)\r\n at QRCode.Base64QRCode.BitmapToBase64(Bitmap bmp, ImageType imgType)\r\n

  15. Joãosays:

    Hello,

    I’m trying to Generate a QR Code from a long string, length = 4180. I’m getting this error message “System.InvalidOperationException: ‘Sequence contains no elements'”.
    I noticed this starts happening when the string length is above 1664. Is there any way to fix this?
    Thanks in advance.

    • Hi JOÃO,

      this isn’t possible. Sure you could lower the error correction level from Q (I think you used it) to L, then you could store 2953 instead of 1663 chars, but that wouldn’t fit. When you convert your string explicitly to ISO-8859-1 it may work, but I can’t promise. (It depents on special characters you use.) In general the QR code specification says clearly where the limits are. Have a look at this table. (Escpecially at the “version list” 31-40.)

      • Joãosays:

        Thanks for your reply. I ended up shortening my string. I’ll try converting it another time.
        Keep up the good work.

  16. zakirsays:

    Hi ,

    Nice Code ,I need to implement custom image by qr code how do i dousing your dll.

    for example I will generate my pic ,logo etc

  17. is this work in Unity if yes then how?

  18. Thanks for your software – we have used your code to generate QR codes so that patients can load the web version of printed patient education handouts easily – over 1200 so far!

  19. Thanks for this library, I did use it to help someone who wants to label drawings.
    https://discourse.mcneel.com/t/qr-code-font/43073/4

  20. Shashikant Pandeysays:

    I use This code Generate barcode Image and i able to generate but in some cases wrong image is generated.
    for example:-
    “string barcode=”300388156602”;

    QRCodeGenerator qrGenerator = new QRCodeGenerator();
    QRCodeGenerator.QRCode qrCode = qrGenerator.CreateQrCode(barcode,QRCodeGenerator.ECCLevel.Q);
    qrCode.GetGraphic(20).Save(“D:/BarcodeImages/300388156602.png”);”
    for This number “300388156602” when i scan barcode image output is “300388140602” but it should be “300388156602”.
    please help what wrong with my code.

    • Hey Shashikant,
      three questions:
      1) From where did you get the QrCoder.dll?
      2) Which version of the dll do you use? (See dll file properties or read addemlby info.)
      3) Which QrCode reader do you use, when you get the wrong output?

      It’s important for me to get this answers because in my setup everything is working fine. So I need to know your setup, to find out whats going wrong.

      • Arslansays:

        Hi Raffael
        QRCoderDemoUWP_temporaryKey.pfx file is always missing.

        • Since this is my “private” key I don’t upload it. Just create your own key via Visual Studio to sign the app.

  21. 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

  22. 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.

  23. 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.

  24. 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.)

  25. 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

  26. Leonelsays:

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

  27. 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?

  28. Nitin VARMA Manthenasays:

    Nice post! thank you

  29. 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.

  30. 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?

  31. 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

    • In biggest version (40) with lowest error correction level (L) you can save 2953 byte.

  32. 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);

  33. 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.

  34. 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. ;-)

  35. 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.

  36. 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

  37. 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.

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

  39. 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).

  40. 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.

  41. Nayefsays:

    Can it work in ASP.NET application?

  42. 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()

  43. saqisays:

    why i am getting white background picturbox ?

  44. 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?

  45. 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?

    • ositasays:

      Hello…pls how did u tailor it’s use to unity 3d???… I’m running a project on unity and it seems I need that too

  46. 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

  47. AV Awesomesays:

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

  48. O'Briansays:

    Very nice project. Easy to use.

    A QR decoder would be nice :-)

Leave a Reply to Raffi Cancel reply

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