How To Generate Barcode And Read The Barcode In MVC

What is a barcode?

A barcode is a small image of lines (bars) and spaces that is affixed to retail store items, identification cards, and postal mail to identify a particular product number, person, or location. The code uses a sequence of vertical bars and spaces to represent numbers and other symbols. A bar code symbol typically consists of five parts: a quiet zone, a start character, and data character a stop character, and another quiet zone.

Now, we will see how to generate the barcode. Let us see step by step.

Step 1

First, we have to download the Free Barcode Font from this link or also this link

->After downloading the file, we extract the ZIP file.
-> Click and Execute INSTALL.exe file.
-> After installation is completed restart our machine.

Step 2

Open our Visual Studio and create a web application in MVC. After that, we add a controller and add an action to get action method.

  1. public ActionResult GenerateBarCode()  
  2. {  
  3.     return View();  
  4. }  

Now, we need to add a View and design the our View page using HTML.

  1. @using (Html.BeginForm("GenerateBarCode""BarCodeDemo", FormMethod.Post))  
  2. {  
  3. <div class="row">  
  4.     <div class="col-md-3"></div>  
  5.     <div class="col-md-6">  
  6.         <h2>Generate Bar Code</h2>  
  7.         <input type="text" name="barcode" Class="form-control col-4" ID="textCode" />  
  8.         <br /><br />  
  9.         <input type="submit" Class="btn btn-primary" ID="btnGenerate" value="Generate" />  
  10.         <hr />  
  11.   
  12.         @if (ViewBag.BarcodeImage != null)  
  13.         {  
  14.             <img src="@ViewBag.BarcodeImage" alt="" />  
  15.         }  
  16.     </div>
  17. </div>  
  18. }  

After that we will create a post action method and write the below code.

  1. [HttpPost]    
  2. public ActionResult GenerateBarCode(string barcode)    
  3. {    
  4.     using (MemoryStream memoryStream = new MemoryStream())    
  5.     {    
  6.         using (Bitmap bitMap = new Bitmap(barcode.Length * 40, 80))    
  7.         {    
  8.             using (Graphics graphics = Graphics.FromImage(bitMap))    
  9.             {    
  10.                 Font oFont = new Font("IDAutomationHC39M", 16);    
  11.                 PointF point = new PointF(2f, 2f);    
  12.                 SolidBrush whiteBrush = new SolidBrush(Color.White);    
  13.                 graphics.FillRectangle(whiteBrush, 0, 0, bitMap.Width, bitMap.Height);    
  14.                 SolidBrush blackBrush = new SolidBrush(Color.DarkBlue);    
  15.                 graphics.DrawString("*" + barcode + "*", oFont, blackBrush, point);    
  16.             }  
  17.             bitMap.Save(memoryStream, ImageFormat.Jpeg);  
  18.             ViewBag.BarcodeImage = "data:image/png;base64," + Convert.ToBase64String(memoryStream.ToArray());    
  19.         }    
  20.     }  
  21.     return View();    
  22. } 

In the above code I used many classes and properties; let's see what the uses of  given classes and properties are step by step

Barcode in MVC

  1. MemoryStream
    Creates a stream whose backing store is memory.

  2. Bitmap
    Encapsulates a GDI+ bitmap, which consists of the pixel data for a graphics image and its attributes. A System.Drawing.Bitmap is an object used to work with images defined by pixel data.

  3. Graphics
    Encapsulates a GDI+ drawing surface.

  4. FromImage
    Creates a new System.Drawing.Graphics from the specified System.Drawing.Image. System.Drawing.Image from which to create the new System.Drawing.Graphics.

  5. Font
    The installed Barcode font.

  6. PointF
    Represents an ordered pair of floating-point x- and y-coordinates that defines a point in a two-dimensional plane.

  7. SolidBrush
    Defines a brush of a single color. Brushes are used to fill graphics shapes, such as rectangles, ellipses, pies, polygons, and paths. This class cannot be inherited. 

    Barcode in MVC

  8. ImageFormat
    Specifies the file format of the image. And we can set multiple types of images and  can choose any one.

    Barcode in MVC

Step 3

Now we will run the project and give the input number and click generate button and see the result

Barcode in MVC
Step4

Now we will see how can we read the Barcode and find the actual value.

But we don’t have any bar code scanner so we can check by uploading the bar code image.

Before continuing the next process, we have to Download the barcode reader dll. For downloading the dll go to this link and click download now button on right side. After that extract and add that ddl file in our project.

After Completing the barcode reader we create an action method for the reader,

  1. public ActionResult BarCodeRead()  
  2. {  
  3.     return View();  
  4. }  

After create action method right click and add a view and design.

  1. @using (Html.BeginForm("BarCodeRead""BarCodeDemo", FormMethod.Post,new { @enctype = "multipart/form-data" }))   
  2. {  
  3. <div class="row">  
  4.   
  5.     <div class="col-md-3"></div>  
  6.     <div class="col-md-3">  
  7.         <div align="center">  
  8.             <br />  
  9.             <input type="file" name="barCodeUpload" Class="form-control" ID="barCodeUpload" /><br />  
  10.             <br />  
  11.             <input type="submit" Class="btn btn-primary" ID="UploadButton" value="Upload">  
  12.             <br />  
  13.             <br />  
  14.             <span Class="btn alert-danger">@ViewBag.ErrorMessage</span>  
  15.             <br />  
  16.             <input type="text" Class="form-control col-md-8" value="@ViewBag.BarCode" /><br />  
  17.             <br />  
  18.             <img type="image" src="@ViewBag.BarImage"/>  
  19.         </div>  
  20.   
  21.     </div>  
  22. </div>  
  23. }  

After that we will create post method,

  1. [HttpPost]    
  2. public ActionResult BarCodeRead(HttpPostedFileBase barCodeUpload)    
  3. {    
  4.     String localSavePath = "~/UploadFiles/";    
  5.     string str = string.Empty;    
  6.     string strImage = string.Empty;    
  7.     string strBarCode = string.Empty;  
  8.     if (barCodeUpload != null)    
  9.     {    
  10.         String fileName = barCodeUpload.FileName;    
  11.         localSavePath += fileName;    
  12.         barCodeUpload.SaveAs(Server.MapPath(localSavePath));  
  13.         Bitmap bitmap = null;    
  14.         try    
  15.         {    
  16.             bitmap = new Bitmap(barCodeUpload.InputStream);    
  17.         }    
  18.         catch (Exception ex)    
  19.         {    
  20.             ex.ToString();    
  21.         }  
  22.         if (bitmap == null)    
  23.         {  
  24.             str = "Your file is not an image";   
  25.         }    
  26.         else    
  27.         {    
  28.             strImage = "http://localhost:" + Request.Url.Port + "/UploadFiles/" + fileName;  
  29.             strBarCode = ReadBarcodeFromFile(Server.MapPath(localSavePath));  
  30.         }    
  31.     }    
  32.     else    
  33.     {    
  34.         str = "Please upload the bar code Image.";    
  35.     }    
  36.     ViewBag.ErrorMessage = str;    
  37.     ViewBag.BarCode = strBarCode;    
  38.     ViewBag.BarImage = strImage;    
  39.     return View();    
  40. }    
  41. private String ReadBarcodeFromFile(string _Filepath)    
  42. {    
  43.     String[] barcodes = BarcodeScanner.Scan(_Filepath, BarcodeType.Code39);    
  44.     return barcodes[0];    
  45. } 

Now we will run the project,

Barcode in MVC

When we click the upload button without selecting any file then check the validation,

Barcode in MVC

When we click the upload button with our BarCode Image then see the output

Barcode in MVC

Conclusion

We saw how to generate BarCode image and after that how read our bar code image and find original value then we can save in database.

Note
We can also use Reader class for reading the barcode image and for this we have to install Bytescout.BarCode.Reader dll. So for this just copy the below code. And then Go to tool option in Visual Studio and go to new get package manager -> Package Manager Console and press enter.

Install-Package Bytescout.BarCode.Reader -Version 10.1.0.1788 

Then we can use Reader class like below

Reader reader = new Reader();

Thanks, I hope this article was helpful.


Similar Articles