Generate QR Code in .NET Core Using Bitmap

Introduction

 
As per Wikipedia, 'QR code' (abbreviated from Quick Response code) is the trademark for a type of matrix barcode (or two-dimensional barcode) is a machine-readable optical label that contains information about the item to which it is attached.
 
QR Codes can also be found in more and more places in our daily lives. Although they were 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.
 
So, let's create a .NET Core application and see how a QR code is generated. 
 
Step 1
 
Let's create a .NET Core MVC application.
 
File >> New Project >> ASP .NET Core Web Application >> Choose MVC as Web Template 
 
Generate QR Code In .NET Core Using Bitmap
 
Step 2
 
Install QRCoder via NuGet Package Manager. Also, you can add the package through Nuget Package manager console following this command:
 
Install-Package QRCoder.
 
Generate QR Code In .NET Core Using Bitmap
 
Step 3
 
Add another package Microsoft.AspNetCore.Mvc.TagHelpers through Nuget, as we use the tag helper to access the controller.
 
 
Generate QR Code In .NET Core Using Bitmap
 
Step 4
 
Now add the below design in "Index.cshtml". We have taken one input field and typed some text, then clicked on the button so that it will generate QR Code for us. 
 
Generate QR Code In .NET Core Using Bitmap
 
Below is the Index.cshtml code:
  1. @model Byte[]      
  2.  @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers      
  3.  @{      
  4.    ViewData["Title"] = "Home Page";      
  5.  }      
  6.  <!DOCTYPE html>      
  7.  <meta name="viewport" content="width=device-width" />      
  8.  <title>Index</title>      
  9.  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">      
  10.  @section Scripts{      
  11.  }      
  12.  <form asp-action="Index" asp-controller="Home" asp-antiforgery="true">      
  13.    <div class="container">      
  14.      <div class="panel-group">      
  15.        <div class="panel panel-info">      
  16.          <div class="panel-heading">Generate QR Code</div>      
  17.          <div class="panel-body">      
  18.            <div class="row">      
  19.              <div class="col-md-12">      
  20.                <div class="col-md-3">Type text to generate QR Code</div>      
  21.                <div class="col-md-9"><input type="text" class="form-control" id="txtQRCode" name="txtQRCode" /></div>      
  22.              </div>      
  23.            </div>      
  24.            <div class="row mt-3">      
  25.              <div class="col-md-12">      
  26.                <div class="col-md-3"></div>      
  27.                <div class="col-md-9">      
  28.                  <input type="submit" class="btn btn-primary" id="btnSubmit" value="Generate QR Code" autocomplete="off" />      
  29.                </div>      
  30.              </div>      
  31.            </div>      
  32.            @{      
  33.              if (Model != null)      
  34.              {      
  35.                <div class="row mt-3">      
  36.                  <div class="col-md-12">      
  37.                    <div class="col-md-3"></div>      
  38.                    <div class="col-md-9">      
  39.                      <img src="@String.Format("data:image/png;base64,{0}", Convert.ToBase64String(Model))" height="300" width="300"/>      
  40.                    </div>      
  41.                  </div>      
  42.                </div>      
  43.              }      
  44.            }      
  45.          </div>      
  46.        </div>      
  47.      </div>      
  48.    </div>      
  49.  </form>       
Code Explanation 
  • We use the Taghelper class to call the controller and take whatever we type in an input box, then send it to the action method when the button is clicked.
  • Once the QR Code is generated by the Index Action method, ‘byte’ array is returned to the View as a model and then the bitmap image is displayed via the below code:
    1. if (Model != null)      
    2.              {      
    3.                <div class="row mt-3">      
    4.                  <div class="col-md-12">      
    5.                    <div class="col-md-3"></div>      
    6.                    <div class="col-md-9">      
    7.       <img src="@String.Format("data:image/png;base64,{0}",       
    8.  Convert.ToBase64String(Model))" height="300" width="300"/>      
    9.                    </div>      
    10.                  </div>      
    11.                </div>      
    12.              }     
Step 5
 
Add the Index Post method inside the Home controller like below.
  1. [ValidateAntiForgeryToken]      
  2.      [HttpPost]      
  3.      public IActionResult Index(string txtQRCode) {      
  4.        QRCodeGenerator _qrCode = new QRCodeGenerator();      
  5.        QRCodeData _qrCodeData = _qrCode.CreateQrCode(txtQRCode,QRCodeGenerator.ECCLevel.Q);      
  6.        QRCode qrCode = new QRCode(_qrCodeData);      
  7.        Bitmap qrCodeImage = qrCode.GetGraphic(20);      
  8.        return View(BitmapToBytesCode(qrCodeImage));      
  9.      }      
  10.      [NonAction]      
  11.      private static Byte[] BitmapToBytesCode(Bitmap image)      
  12.      {      
  13.        using (MemoryStream stream = new MemoryStream())      
  14.        {      
  15.          image.Save(stream, System.Drawing.Imaging.ImageFormat.Png);      
  16.          return stream.ToArray();      
  17.        }      
  18.      }      
Code Explanation 
  • This Index Action receives a string parameter. It contains the text that is provided by an Input control defined in the View. This text will be converted to QR Code Bitmap image.
  • The QRCode object ('qrCode') defined calls a static function called 'BitmapToBytesCode()'. The role of this function is to convert the Bitmap image to 'Byte[]'.
Step 6
 
Now run the application and see the output like below. Type the text in the input box and hit enter on Button it will generate the Bitmap Image like above. Then scan the QR Code and you can see the text.
 
Generate QR Code In .NET Core Using Bitmap
 
When we scan any QR Code reader using mobile or anything else, you can get the result.
 
Generate QR Code In .NET Core Using Bitmap
 


Similar Articles