QR Code Generator in MVC C#
Install the following component for QR Code Generation.
C# Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Gma.QrCodeNet.Encoding;
using Gma.QrCodeNet.Encoding.Windows.Render;
using System.Data;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
namespace QRPrint.Controllers
{
public class QRControlController : Controller
{
string filepath = HttpRuntime.AppDomainAppPath;
[HttpGet]
public ActionResult Display(String txt="")
{
try
{
if(txt!="")
{
QRCodeImage(txt);
ViewBag.txt = txt + ".png";
}
return View();
}
catch
(Exception ex)
{
return View();
}
}
[HttpPost]
public ActionResult Display(FormCollection Data)
{
string name = Convert.ToString(Data["txtname"]);
return RedirectToAction("Display",new { txt=name });
}
public ActionResult QRCodeImage(String Text)
{
// generating a barcode here. Code is taken from
QrCode.Net library
QrEncoder qrEncoder = new
QrEncoder(ErrorCorrectionLevel.H);
QrCode qrCode = new QrCode();
qrEncoder.TryEncode(Text, out qrCode);
System.Web.UI.WebControls.Image imgBarCode = new System.Web.UI.WebControls.Image();
imgBarCode.Height = 150;
imgBarCode.Width = 150;
GraphicsRenderer renderer = new
GraphicsRenderer(new FixedModuleSize(4, QuietZoneModules.Four), Brushes.Black, Brushes.White);
MemoryStream memoryStream = new
MemoryStream();
renderer.WriteToStream(qrCode.Matrix, ImageFormat.Png, memoryStream);
// very important to reset memory stream to a starting
position, otherwise you would get 0 bytes returned
memoryStream.Position = 0;
var
resultStream = new FileStreamResult(memoryStream, "image/png");
resultStream.FileDownloadName = String.Format("{0}.png", Text);
// Save To Drive
byte[]
byteImage = memoryStream.ToArray();
if
(!Directory.Exists(filepath))
Directory.CreateDirectory(filepath);
string fileLocation = filepath + Text + ".png";
using
(MemoryStream ms = new MemoryStream(byteImage))
{
using (Bitmap bm2 = new Bitmap(ms))
{
if (System.IO.File.Exists(fileLocation))
{
System.IO.File.Delete(fileLocation);
}
bm2.Save(filepath + "\\Images\\" + Text + ".png");
}
}
return resultStream;
}
}
}
View Page:
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Display</title>
<script>
$(document).ready(function () {
var
name = '@Request.QueryString["txt"]';
});
</script>
</head>
<body>
<div>
<form method="post">
Name: <input type="text" id="txtname" name="txtname" />
<input type="submit" value="QR Gen" />
<img src="~/Images/@ViewBag.txt" height="220" width="220"/>
</form>
</div>
</body>
</html>
Excellent post to qr code, would like to add few more helpful posts like
ReplyDeleteWeb API token authentication in C#
Import CSV in SQL Server
Thanks