How to Create a QR Code with .Net 6+

QR codes are a nice way to supply your users with an URL without letting them type it into their mobile devices. All they need to do is to point their camera to the QR code and scan it. There are many libraries to create QR codes with .Net. Unfortunately, not all are working with .Net 6 and newer. In this post we explore a user-friendly library that works with .Net 6 and .Net 7.

 

What is the big deal with .Net 6 and QR codes?

Most libraries used the namespace System.Drawing.Common to create the QR code images. Starting with .Net 6 this namespace is only supported on Windows. For Linux, Mac and your cross-platform applications you need an alternative implementation.

Since the .Net community has no clear favourite replacement, some libraries are still waiting on a winner. Other libraries did not want to rewrite their code and stopped the development entirely. Therefore, if you pick a library with a graphic component, make sure that the project found a way forward and is actively maintained.

 

Installation

I settled with the package Net.Codecrete.QrCodeGenerator to create my QR codes. You can install it by running this command in the Package Manager Console:

To solve the System.Drawing.Common problem, you can choose the alternative you like the most and download the matching extension methods from the GitHub repository. These 3 options are currently supported:

  • System.Drawing (for Windows-only projects)
  • SkiaSharp
  • ImageSharp

You can put the extension methods class wherever you want inside your project.

 

Create a QR code image

To create a QR code, we call the static method EncodeText() with our text and the level of error correcting that we find helpful. We can use the method SaveAsPng() to save the generated code image to the disk:

This should create us an image like this one that we can scan with our mobile phone to open the URL of this blog:

The generated QR code

 

Create a QR code for the web

Inside our web application we can use the same method to create the QR code. Since we want to send the image to the client, we do not need to store it on the file system. Instead, we can use the method ToPng() to get a byte array that we can send back as a response:

Especially when we want to scale the QR code a PNG may not be the best solution. With the method ToSvgString() we can define a border around our (scalable) SVG image:

 

Conclusion

Net.Codecrete.QrCodeGenerator is a great help to create QR codes in .Net 6+. With the extension methods we get the flexibility we need to go forward without the System.Drawing.Common namespace. Try it!

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.