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.
- public ActionResult GenerateBarCode()
- {
- return View();
- }
Now, we need to add a View and design the our View page using HTML.
- @using (Html.BeginForm("GenerateBarCode", "BarCodeDemo", FormMethod.Post))
- {
- <div class="row">
- <div class="col-md-3"></div>
- <div class="col-md-6">
- <h2>Generate Bar Code</h2>
- <input type="text" name="barcode" Class="form-control col-4" ID="textCode" />
- <br /><br />
- <input type="submit" Class="btn btn-primary" ID="btnGenerate" value="Generate" />
- <hr />
-
- @if (ViewBag.BarcodeImage != null)
- {
- <img src="@ViewBag.BarcodeImage" alt="" />
- }
- </div>
- </div>
- }
After that we will create a post action method and write the below code.
- [HttpPost]
- public ActionResult GenerateBarCode(string barcode)
- {
- using (MemoryStream memoryStream = new MemoryStream())
- {
- using (Bitmap bitMap = new Bitmap(barcode.Length * 40, 80))
- {
- using (Graphics graphics = Graphics.FromImage(bitMap))
- {
- Font oFont = new Font("IDAutomationHC39M", 16);
- PointF point = new PointF(2f, 2f);
- SolidBrush whiteBrush = new SolidBrush(Color.White);
- graphics.FillRectangle(whiteBrush, 0, 0, bitMap.Width, bitMap.Height);
- SolidBrush blackBrush = new SolidBrush(Color.DarkBlue);
- graphics.DrawString("*" + barcode + "*", oFont, blackBrush, point);
- }
- bitMap.Save(memoryStream, ImageFormat.Jpeg);
- ViewBag.BarcodeImage = "data:image/png;base64," + Convert.ToBase64String(memoryStream.ToArray());
- }
- }
- return View();
- }
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
- MemoryStream
Creates a stream whose backing store is memory.
- 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.
- Graphics
Encapsulates a GDI+ drawing surface.
- 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.
- Font
The installed Barcode font.
- PointF
Represents an ordered pair of floating-point x- and y-coordinates that defines a point in a two-dimensional plane.
- 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.
- ImageFormat
Specifies the file format of the image. And we can set multiple types of images and can choose any one.
Step 3
Now we will run the project and give the input number and click generate button and see the result
Step4Now 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,
- public ActionResult BarCodeRead()
- {
- return View();
- }
After create action method right click and add a view and design.
- @using (Html.BeginForm("BarCodeRead", "BarCodeDemo", FormMethod.Post,new { @enctype = "multipart/form-data" }))
- {
- <div class="row">
-
- <div class="col-md-3"></div>
- <div class="col-md-3">
- <div align="center">
- <br />
- <input type="file" name="barCodeUpload" Class="form-control" ID="barCodeUpload" /><br />
- <br />
- <input type="submit" Class="btn btn-primary" ID="UploadButton" value="Upload">
- <br />
- <br />
- <span Class="btn alert-danger">@ViewBag.ErrorMessage</span>
- <br />
- <input type="text" Class="form-control col-md-8" value="@ViewBag.BarCode" /><br />
- <br />
- <img type="image" src="@ViewBag.BarImage"/>
- </div>
-
- </div>
- </div>
- }
After that we will create post method,
- [HttpPost]
- public ActionResult BarCodeRead(HttpPostedFileBase barCodeUpload)
- {
- String localSavePath = "~/UploadFiles/";
- string str = string.Empty;
- string strImage = string.Empty;
- string strBarCode = string.Empty;
- if (barCodeUpload != null)
- {
- String fileName = barCodeUpload.FileName;
- localSavePath += fileName;
- barCodeUpload.SaveAs(Server.MapPath(localSavePath));
- Bitmap bitmap = null;
- try
- {
- bitmap = new Bitmap(barCodeUpload.InputStream);
- }
- catch (Exception ex)
- {
- ex.ToString();
- }
- if (bitmap == null)
- {
- str = "Your file is not an image";
- }
- else
- {
- strImage = "http://localhost:" + Request.Url.Port + "/UploadFiles/" + fileName;
- strBarCode = ReadBarcodeFromFile(Server.MapPath(localSavePath));
- }
- }
- else
- {
- str = "Please upload the bar code Image.";
- }
- ViewBag.ErrorMessage = str;
- ViewBag.BarCode = strBarCode;
- ViewBag.BarImage = strImage;
- return View();
- }
- private String ReadBarcodeFromFile(string _Filepath)
- {
- String[] barcodes = BarcodeScanner.Scan(_Filepath, BarcodeType.Code39);
- return barcodes[0];
- }
Now we will run the project,
When we click the upload button without selecting any file then check the validation,
When we click the upload button with our BarCode Image then see the output
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.