Install IronBarcode

The first step in the journey will be installing IronBarcode, which can be done by downloading from NuGet or by downloading the DLL.

To install the IronBarcode NuGet package, you could use the NuGet Package Manager for Visual Studio:

Install-Package BarCode

Alternatively, you could also install with the dotnet CLI:

dotnet add package IronBarCode

Reading a Barcode or QR Code

Reading a barcode only takes one line of code with IronBarcode.

:path=/static-assets/barcode/content-code-examples/get-started/get-started-1.cs
using IronBarCode; // Import the IronBarCode library for barcode reading and generation.

// Attempt to read barcodes from an image file named "QuickStart.jpg"
BarcodeResults results = BarcodeReader.Read("QuickStart.jpg");

// Check if any barcodes are detected in the image
if (results != null && results.Count > 0)
{
    // Loop through each detected barcode result
    foreach (BarcodeResult result in results)
    {
        // Output the text value of each barcode to the console
        Console.WriteLine(result.Text);
    }
}
else
{
    // Output a message if no barcodes are detected
    Console.WriteLine("No barcodes found in the image.");
}
Imports IronBarCode ' Import the IronBarCode library for barcode reading and generation.



' Attempt to read barcodes from an image file named "QuickStart.jpg"

Private results As BarcodeResults = BarcodeReader.Read("QuickStart.jpg")



' Check if any barcodes are detected in the image

If results IsNot Nothing AndAlso results.Count > 0 Then

	' Loop through each detected barcode result

	For Each result As BarcodeResult In results

		' Output the text value of each barcode to the console

		Console.WriteLine(result.Text)

	Next result

Else

	' Output a message if no barcodes are detected

	Console.WriteLine("No barcodes found in the image.")

End If
$vbLabelText   $csharpLabel

With this one line of code, you have the ability to detect and scan all types of barcodes from the input document with exceptional performance—everything you need in one step! This method supports a wide range of image formats, such as JPEG, PNG, and BMP, as well as PDFs and multi-frame formats like GIF and TIFF. For enhanced performance, customizable configuration options are available.

To improve reading speed, you can create a BarcodeReaderOptions object with the Speed setting configured for better performance. The default is Balanced, but the Faster option is available to skip certain checks.

:path=/static-assets/barcode/content-code-examples/get-started/get-started-2.cs
// Import the necessary library for barcode reading.
using IronBarCode;
using System;
using System.Linq;

// Configure barcode reader options.
BarcodeReaderOptions myOptionsExample = new BarcodeReaderOptions
{
    // Expect a single barcode in the image.
    ExpectMultipleBarcodes = false,

    // Specify the types of barcodes we expect to find.
    // In this case, QR Code and Code 128.
    ExpectedBarcodeTypes = BarcodeEncoding.QRCode 
 BarcodeEncoding.Code128,

    // Define the area of the image to crop for scanning the barcode.
    // X: 100, Y: 200, Width: 300, Height: 400.
    CropArea = new System.Drawing.Rectangle(100, 200, 300, 400)
};

// Read the barcode from the specified image file.
BarcodeResults results = BarcodeReader.Read("QuickStart.jpg", myOptionsExample);

// Check if any barcodes were read successfully.
if (results != null && results.Count > 0)
{
    // Output the text from the first barcode found.
    Console.WriteLine(results.First().Text);
}
else
{
    // No barcodes found or an error occurred.
    Console.WriteLine("No barcodes were detected in the image.");
}
' Import the necessary library for barcode reading.

Imports IronBarCode

Imports System

Imports System.Linq



' Configure barcode reader options.

Private myOptionsExample As New BarcodeReaderOptions With {

	.ExpectMultipleBarcodes = False,

	.ExpectedBarcodeTypes = BarcodeEncoding.QRCode Or BarcodeEncoding.Code128,

	.CropArea = New System.Drawing.Rectangle(100, 200, 300, 400)

}



' Read the barcode from the specified image file.

Private results As BarcodeResults = BarcodeReader.Read("QuickStart.jpg", myOptionsExample)



' Check if any barcodes were read successfully.

If results IsNot Nothing AndAlso results.Count > 0 Then

	' Output the text from the first barcode found.

	Console.WriteLine(results.First().Text)

Else

	' No barcodes found or an error occurred.

	Console.WriteLine("No barcodes were detected in the image.")

End If
$vbLabelText   $csharpLabel

You can also set the ScanMode to OnlyBasicScan to optimize the reading process.

:path=/static-assets/barcode/content-code-examples/get-started/get-started-3.cs
using IronBarCode; // Using the IronBarCode library for barcode reading
using System;
using System.Drawing; // Required for using Bitmap

// Read barcodes from the specified image.
var results = BarcodeReader.Read("MultipleBarcodes.png");

// Check if any barcodes were found
if (results != null && results.Length > 0)
{
    // Loop through each result obtained from the image
    foreach (BarcodeResult result in results)
    {
        // Obtain the textual value from the barcode
        string value = result.Value;

        // Obtain the image representation of the barcode
        Bitmap img = result.BarcodeImage;

        // Obtain the barcode encoding type (such as QR, Code 128, etc.)
        BarcodeEncoding barcodeType = result.BarcodeType;

        // Obtain the binary value of the barcode, which is often useful for more advanced processing
        byte[] binary = result.BinaryValue;

        // Output the barcode's value to the console
        Console.WriteLine($"Value: {value}");

        // Optional: Output additional details for each barcode
        Console.WriteLine($"Type: {barcodeType}");
        Console.WriteLine($"Binary Value: {BitConverter.ToString(binary)}");
    }
}
else
{
    // Output if no barcodes are found
    Console.WriteLine("No barcodes found in the image.");
}
Imports IronBarCode ' Using the IronBarCode library for barcode reading

Imports System

Imports System.Drawing ' Required for using Bitmap



' Read barcodes from the specified image.

Private results = BarcodeReader.Read("MultipleBarcodes.png")



' Check if any barcodes were found

If results IsNot Nothing AndAlso results.Length > 0 Then

	' Loop through each result obtained from the image

	For Each result As BarcodeResult In results

		' Obtain the textual value from the barcode

		Dim value As String = result.Value



		' Obtain the image representation of the barcode

		Dim img As Bitmap = result.BarcodeImage



		' Obtain the barcode encoding type (such as QR, Code 128, etc.)

		Dim barcodeType As BarcodeEncoding = result.BarcodeType



		' Obtain the binary value of the barcode, which is often useful for more advanced processing

		Dim binary() As Byte = result.BinaryValue



		' Output the barcode's value to the console

		Console.WriteLine($"Value: {value}")



		' Optional: Output additional details for each barcode

		Console.WriteLine($"Type: {barcodeType}")

		Console.WriteLine($"Binary Value: {BitConverter.ToString(binary)}")

	Next result

Else

	' Output if no barcodes are found

	Console.WriteLine("No barcodes found in the image.")

End If
$vbLabelText   $csharpLabel

Other configurations include specifying the barcode formats to scan for, which can help speed up processing by reducing unnecessary scans.

:path=/static-assets/barcode/content-code-examples/get-started/get-started-4.cs
using IronBarCode;
using System;
using System.Drawing;

// Read barcodes from a PDF file
BarcodeResults pagedResults = BarcodeReader.Read("MultipleBarcodes.pdf");

// Iterate through each barcode result found in the PDF file
foreach (BarcodeResult result in pagedResults)
{
    int pageNumber = result.PageNumber;            // Get the page number where the barcode was detected
    string value = result.Value;                   // Extract the decoded value of the barcode
    Bitmap img = result.BarcodeImage;              // Fetch the image of the barcode
    BarcodeEncoding barcodeType = result.BarcodeType; // Determine the type of barcode encoding
    byte[] binary = result.BinaryValue;            // Extract the binary data of the barcode

    // Log barcode details to the console
    Console.WriteLine($"Page: {pageNumber}, Value: {value}, Type: {barcodeType}");
}

// Read barcodes from a multi-page TIFF file with specified options for detailed analysis
BarcodeResults multiFrameResults = BarcodeReader.Read(inputImage: "Multiframe.tiff", new BarcodeReaderOptions
{
    Speed = ReadingSpeed.Detailed,                  // Set to detailed for thorough reading
    ExpectMultipleBarcodes = true,                  // Assume multiple barcodes might exist per page
    ExpectBarcodeTypes = BarcodeEncoding.CODE128,   // Anticipate a specific type of barcode encoding
    Multithreaded = false,                          // Run analysis on a single thread
    RemoveFalsePositive = false,                    // Choose not to filter out potential false positives
    ImageFilters = null                             // Do not apply any additional image processing filters
});

// Iterate over each barcode result from the multi-frame TIFF file
foreach (BarcodeResult result in multiFrameResults)
{
    Console.WriteLine($"Page: {result.PageNumber}, Value: {result.Value}, Type: {result.BarcodeType}");
}
Imports IronBarCode

Imports System

Imports System.Drawing



' Read barcodes from a PDF file

Private pagedResults As BarcodeResults = BarcodeReader.Read("MultipleBarcodes.pdf")



' Iterate through each barcode result found in the PDF file

For Each result As BarcodeResult In pagedResults

	Dim pageNumber As Integer = result.PageNumber ' Get the page number where the barcode was detected

	Dim value As String = result.Value ' Extract the decoded value of the barcode

	Dim img As Bitmap = result.BarcodeImage ' Fetch the image of the barcode

	Dim barcodeType As BarcodeEncoding = result.BarcodeType ' Determine the type of barcode encoding

	Dim binary() As Byte = result.BinaryValue ' Extract the binary data of the barcode



	' Log barcode details to the console

	Console.WriteLine($"Page: {pageNumber}, Value: {value}, Type: {barcodeType}")

Next result



' Read barcodes from a multi-page TIFF file with specified options for detailed analysis

Dim multiFrameResults As BarcodeResults = BarcodeReader.Read(inputImage:= "Multiframe.tiff", New BarcodeReaderOptions With {

	.Speed = ReadingSpeed.Detailed,

	.ExpectMultipleBarcodes = True,

	.ExpectBarcodeTypes = BarcodeEncoding.CODE128,

	.Multithreaded = False,

	.RemoveFalsePositive = False,

	.ImageFilters = Nothing

})



' Iterate over each barcode result from the multi-frame TIFF file

For Each result As BarcodeResult In multiFrameResults

	Console.WriteLine($"Page: {result.PageNumber}, Value: {result.Value}, Type: {result.BarcodeType}")

Next result
$vbLabelText   $csharpLabel

Writing Barcodes

To write barcodes using IronBarcode, we use the BarcodeWriter class.

:path=/static-assets/barcode/content-code-examples/get-started/get-started-5.cs
using IronBarCode;

// This code demonstrates how to generate a barcode from a URL using the IronBarCode library
// and save it as an image file.

// Generate a barcode with the given URL and a specified encoding type
GeneratedBarcode myBarcode = BarcodeWriter.CreateBarcode(
    "https://ironsoftware.com/csharp/barcode", // The data to encode in the barcode
    BarcodeEncoding.Code128 // The type of encoding to use - Code128 is a widely used option
);

// Save the generated barcode as a PNG image file
myBarcode.SaveAsImage("myBarcode.png"); // Filename of the image to save the barcode in
Imports IronBarCode



' This code demonstrates how to generate a barcode from a URL using the IronBarCode library

' and save it as an image file.



' Generate a barcode with the given URL and a specified encoding type

Private myBarcode As GeneratedBarcode = BarcodeWriter.CreateBarcode("https://ironsoftware.com/csharp/barcode", BarcodeEncoding.Code128)



' Save the generated barcode as a PNG image file

myBarcode.SaveAsImage("myBarcode.png") ' Filename of the image to save the barcode in
$vbLabelText   $csharpLabel

Styling Barcodes

IronBarcode offers several options to manipulate the visual depiction of a barcode.

:path=/static-assets/barcode/content-code-examples/get-started/get-started-7.cs
using IronBarCode;

// This script generates a barcode using the IronBarCode library.
// It encodes a URL as a Code128 barcode, applies some customizations,
// and saves it as a PNG image.

try
{
    // Create a barcode from the provided URL with Code128 encoding
    GeneratedBarcode myBarcode = BarcodeWriter.CreateBarcode(
        "https://ironsoftware.com/csharp/barcode",
        BarcodeEncoding.Code128
    );

    // Add a label above the barcode specifying the content of the barcode
    myBarcode.AddAnnotationTextAboveBarcode("Product URL:");

    // Add the value of the barcode (the URL) below the barcode itself
    myBarcode.AddBarcodeValueTextBelowBarcode();

    // Set the margins around the barcode
    myBarcode.SetMargins(100);

    // Change the barcode's color to purple
    myBarcode.ChangeBarCodeColor(IronSoftware.Drawing.Color.Purple);

    // Save the generated barcode as a PNG file
    // All major image formats supported as well as PDF and HTML
    myBarcode.SaveAsPng("myBarcode.png");
}
catch (Exception ex)
{
    // Handle exceptions that might occur during barcode creation or saving
    Console.WriteLine("An error occurred: " + ex.Message);
}
Imports IronBarCode



' This script generates a barcode using the IronBarCode library.

' It encodes a URL as a Code128 barcode, applies some customizations,

' and saves it as a PNG image.



Try

	' Create a barcode from the provided URL with Code128 encoding

	Dim myBarcode As GeneratedBarcode = BarcodeWriter.CreateBarcode("https://ironsoftware.com/csharp/barcode", BarcodeEncoding.Code128)



	' Add a label above the barcode specifying the content of the barcode

	myBarcode.AddAnnotationTextAboveBarcode("Product URL:")



	' Add the value of the barcode (the URL) below the barcode itself

	myBarcode.AddBarcodeValueTextBelowBarcode()



	' Set the margins around the barcode

	myBarcode.SetMargins(100)



	' Change the barcode's color to purple

	myBarcode.ChangeBarCodeColor(IronSoftware.Drawing.Color.Purple)



	' Save the generated barcode as a PNG file

	' All major image formats supported as well as PDF and HTML

	myBarcode.SaveAsPng("myBarcode.png")

Catch ex As Exception

	' Handle exceptions that might occur during barcode creation or saving

	Console.WriteLine("An error occurred: " & ex.Message)

End Try
$vbLabelText   $csharpLabel

Exporting Barcodes as HTML

IronBarcode can export barcodes as HTML documents or as part of HTML content.

:path=/static-assets/barcode/content-code-examples/get-started/get-started-8.cs
// Import the necessary library to work with QR Code generation.
using IronBarCode;

// Create a QR code for the specified URL with specified dimensions and error correction level.
var qrCode = QRCodeWriter.CreateQrCode(
    "https://ironsoftware.com",          // URL to encode in the QR code.
    500,                                 // Pixel size of the QR code in pixels. This defines the resolution of the generated QR code image.
    QRCodeWriter.QrErrorCorrectionLevel.Medium  // Error correction level. Medium level offers a balance between durability and data storage.
);

// Save the generated QR code as a PDF file to the specified path.
// The 'SaveAsPdf' method exports the QR code to a PDF file, ensuring that it maintains high quality and is easy to distribute.
qrCode.SaveAsPdf("MyQR.pdf");
' Import the necessary library to work with QR Code generation.

Imports IronBarCode



' Create a QR code for the specified URL with specified dimensions and error correction level.

Private qrCode = QRCodeWriter.CreateQrCode("https://ironsoftware.com", 500, QRCodeWriter.QrErrorCorrectionLevel.Medium)



' Save the generated QR code as a PDF file to the specified path.

' The 'SaveAsPdf' method exports the QR code to a PDF file, ensuring that it maintains high quality and is easy to distribute.

qrCode.SaveAsPdf("MyQR.pdf")
$vbLabelText   $csharpLabel

Generating QR Codes

For QR codes, use the QRCodeWriter class which provides additional configuration for QR-specific features like error correction.

:path=/static-assets/barcode/content-code-examples/get-started/get-started-9.cs
// Import necessary namespaces
using IronBarCode;
using IronSoftware.Drawing; // Ensure to add this namespace, which may contain required classes and types

// The path to the image file that will be used as a logo in the QR Code
string logoFilePath = "visual-studio-logo.png";

// Create a QRCodeLogo object with the specified logo file
// Ensure that the file path is correct and that the file exists in the specified location
QRCodeLogo qrCodeLogo = new QRCodeLogo(logoFilePath);

// The URL or data to be encoded in the QR Code
string url = "https://ironsoftware.com/csharp/barcode/";

// Generate a QR Code with the logo
// The CreateQrCodeWithLogo method creates a QR code from the given URL and embeds the logo in the center
GeneratedBarcode myQRCodeWithLogo = QRCodeWriter.CreateQrCodeWithLogo(url, qrCodeLogo);

// Change the color of the QR Code to Dark Green and save it as a PDF
// Use the ChangeBarCodeColor method to customize the appearance of the QR code
myQRCodeWithLogo.ChangeBarCodeColor(IronSoftware.Drawing.Color.DarkGreen).SaveAsPdf("MyQRWithLogo.pdf");

// Inform the user that the process is complete
Console.WriteLine("QR Code with logo has been generated and saved as MyQRWithLogo.pdf");
' Import necessary namespaces

Imports IronBarCode

Imports IronSoftware.Drawing ' Ensure to add this namespace, which may contain required classes and types



' The path to the image file that will be used as a logo in the QR Code

Private logoFilePath As String = "visual-studio-logo.png"



' Create a QRCodeLogo object with the specified logo file

' Ensure that the file path is correct and that the file exists in the specified location

Private qrCodeLogo As New QRCodeLogo(logoFilePath)



' The URL or data to be encoded in the QR Code

Private url As String = "https://ironsoftware.com/csharp/barcode/"



' Generate a QR Code with the logo

' The CreateQrCodeWithLogo method creates a QR code from the given URL and embeds the logo in the center

Private myQRCodeWithLogo As GeneratedBarcode = QRCodeWriter.CreateQrCodeWithLogo(url, qrCodeLogo)



' Change the color of the QR Code to Dark Green and save it as a PDF

' Use the ChangeBarCodeColor method to customize the appearance of the QR code

myQRCodeWithLogo.ChangeBarCodeColor(IronSoftware.Drawing.Color.DarkGreen).SaveAsPdf("MyQRWithLogo.pdf")



' Inform the user that the process is complete

Console.WriteLine("QR Code with logo has been generated and saved as MyQRWithLogo.pdf")
$vbLabelText   $csharpLabel

Supported Barcode Formats

IronBarcode supports a wide variety of commonly used barcode formats for both reading and writing:

  • QR, Micro QR, and Rectangular Micro QR (rMQR) codes.
  • Other two-dimensional barcodes such as Aztec, Data Matrix, MaxiCode, and PDF417.
  • Stacked linear barcodes such as Databar.
  • Conventional one-dimensional barcode formats such as UPC-A, UPC-E, EAN-8, EAN-13, Codabar, ITF, MSI, and Plessey.

Why Choose IronBarcode?

IronBarcode offers a friendly, easy-to-use API for developers to read and write barcodes for .NET, which optimizes for accuracy, precision, and speed in real-world use cases.

The BarcodeWriter class, for example, automatically validates and corrects 'checksums' on UPCA and UPCE barcodes, and handles numeric format constraints. IronBarcode assists developers in choosing the most suitable barcode format for their data.

The library is robust, with image pre-processing techniques like automatic rotation and image denoising to maximize barcode detection success rates.

Moving Forward

To get the most out of IronBarcode, we encourage you to read the tutorials within this documentation section, and to visit us on GitHub.