Home.NETASP.NETContact
ASP.NET
Generate QR Code using ASP.NET – C#
Shehryar Khan
Shehryar Khan
July 15, 2022
1 min

Table Of Contents

01
Introduction
02
Creating a Project
03
Installing QRCoder Library
04
Generating QR
05
Coloring QR

Introduction

With the increase of smartphones usage, QR Codes can also be found at more and more places in our daily lives. Although It was initially used to track parts in the manufacturing of vehicles, now these include storing personal information by organizations, transport ticketing, entertainment & commercial tracking. Along with Bar Codes, QR Codes are also in use for product labelling in stores. Companies providing discount offers by scanning QR Codes using your smartphones. In this Article, I’m going to generate a QR Code using Asp.net Core.

Creating a Project

I’m going to use the VS Code for creating an Empty Web Application project using dotnet core. Create a project using this command

dotnet new web

Installing QRCoder Library

QRCoder is available at NuGet. You can Install by using the commands bellow.

Using Package Manager

Install-Package QRCoder

or Using .Net CLI

dotnet add package QRCoder

Generating QR

First of all, update your Startup.cs File with the below Code to ready your project for a Web Application.

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        app.UseStaticFiles();
        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=QR}/{action=Index}/{id?}");
        });
    }
}

Now create new Folders as Controllers & Views at the root directory of your project.

Inside Controllers Folder create a new File as QRController.cs & add this Code.

using System.Drawing;
using System.IO;
using Microsoft.AspNetCore.Mvc;
using QRCoder;

public class QRController : Controller
{
    public ActionResult Index()
    {
        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);

        var bitmapBytes = BitmapToBytes(qrCodeImage); //Convert bitmap into a byte array
        return File(bitmapBytes, "image/jpeg"); //Return as file result
    }

    // This method is for converting bitmap into a byte array
    private static byte[] BitmapToBytes(Bitmap img)
    {
        using (MemoryStream stream = new MemoryStream())
        {
            img.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
            return stream.ToArray();
        }
    }
}

Inside the Index method, I’m generating QR Code. ‘BitmapToBytes’ method is for converting Image bitmap into a bytes array for displaying in an HTML Page.

Now inside Views folder, create a new Folder as QR & inside this Folder create a new File as Index.cshtml

Add the below Code inside your Index.cshtml File

<!DOCTYPE html>
<html>
    <body>;

        <h1>QR Code</h1>
        <img src='@Url.Action("image")' alt="" />

        <script>
            $(document).ready(function () {

                alert('ViewBag.image');
            });
        </script>

    </body>
</html>

Now run your Application. You’ll see this in your Browser.

QR Code
QR Code

Coloring QR

There are also options available to change the Colors of your QR Code.

Inside Index method of your QRController.cs Find this line

Bitmap qrCodeImage = qrCode.GetGraphic(20);

& add colors like this

Bitmap qrCodeImage = qrCode.GetGraphic(20, Color.DarkRed, Color.PaleGreen, true);

Now run your Application again.

you’ll see this.

Colored QR Code
Colored QR Code

If you’re using Linux or MacOS, there is a chance to get this error while generating QR Code.

System.DllNotFoundException: Unable to load DLL ‘libgdiplus‘: The specified module could not be found.

Solution

For Linux, run this command

sudo apt-get install libgdiplus

& for MacOS

brew install mono-libgdiplus

Thank you for reading. Feel free to ask if you have any Question.

I would be happy if you would leave a short comment. I’ll Love to solve your problem If you find any difficulty generating QR Code.

You can also download the complete source code of the above example from GitHub

Related Articles:

A Complete Guide to Secure your ASP.NET Web Application & API

Best Windows Hosting to Host an ASP.NET Application


Tags

#qrcode#csharp
Shehryar Khan

Shehryar Khan

Full-Stack .NET Developer

I'm passionate about learning new technologies as well as mentoring and helping others get started with their programming career. This blog is my way of giving back to the Community.

Expertise

.NET
ASP.NET
React

Social Media

instagramtwitterwebsite

Related Posts

Security
A Complete Guide to Secure your ASP.NET Web Application & API
July 18, 2022
6 min
© 2022, All Rights Reserved.

Quick Links

Advertise with usContact Us

Social Media