How to Generate QR Code using Asp.net Core C#

In this article, we will learn how to Generate a QR Code using Asp.net Core MVC C#. In the previous article, we discussed https://labpys.com/how-to-export-data-from-database-table-to-excel-file-in-asp-net-core-mvc.

Prerequisites

  • Download and install .Net Core 6.0 SDK from here
  • Download and Install Microsoft Visual Studio 2022 from here

Create an ASP.NET Core MVC Project

Open Visual Studio, Go to the File menu click on New, and select Project. Then new project window, select the ASP.NET Core Web Application (Model-View-Controller) template.

Enter a project name and click Create.

Install NuGet Packages for QR Code Generator

  • QRCoder

Create Controller

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

namespace Asp.netcore_Tutorials.Controllers
{
    public class QRCodeController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }

        [HttpPost]
        [AutoValidateAntiforgeryToken]
        public IActionResult Index(string QRtext)
        {
            QRCodeGenerator QRGen = new QRCodeGenerator();
            QRCodeData Qrinfo = QRGen.CreateQrCode(QRtext, QRCodeGenerator.ECCLevel.Q);
            QRCode qRCoder = new QRCode(Qrinfo);

            Bitmap QRbitmap = qRCoder.GetGraphic(50);

            // Color 
            //Bitmap QRbitmap = qRCoder.GetGraphic(50, Color.Blue, Color.Gray, true);

            byte[] bitmapArray = bitmaptoArray(QRbitmap);
            var Qrcodeimage= string.Format("data:image/png;base64,{0}", Convert.ToBase64String(bitmapArray));
            ViewBag.QRCodeImage = Qrcodeimage;
            return View();
        }

        private static byte[] bitmaptoArray(Bitmap bitmapimage)
        {
            using (MemoryStream mstream = new MemoryStream())
            {

                bitmapimage.Save(mstream, ImageFormat.Png);
                return mstream.ToArray();
            }

        }
    }
}

Customize View Index

  
@{
    ViewData["Title"] = "Home Page";
}

<div class="row">
    <div class="col-md-4">
        <form  asp.asp-controller="QRCode" asp-action="Index">
            <div class="form-group">
                <label   class="control-label">QR Code Text</label> 
                <input name="QRtext" class="form-control" />
            </div>
            <div class="form-group">
                <input type="submit" value="Generate QRCode" class="btn btn-primary" />
            </div>
            <div class="form-group">
                <img src="@ViewBag.QRCodeImage" alt="" class="img-thumbnail" />               
            </div> 
        </form>
    </div>
</div>

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments