As you may have read in the Creating a Barcode introductory tutorial, creating, styling, and exporting barcodes as images with IronBarcode is incredibly simple and may often be achieved in a single line of code.

In this example, we will look more in-depth at QR codes, which are becoming increasingly popular in industrial applications and also in retail.

Install QR Code Generator Library in C#

Start using IronBarcode in your project today with a free trial.

First Step:
green arrow pointer
Before we start, we need to install the BarCode NuGet Package.

Install-Package BarCode

https://www.nuget.org/packages/BarCode/

As an alternative, the IronBarCode.Dll can be downloaded and added to your project as a reference from [.NET Barcode DLL].

Importing NameSpaces

For this tutorial, we need to make sure our class files reference IronBarCode and also some normal system assemblies.

using IronBarCode;
using System;
using System.Drawing;
using System.Linq;
using IronBarCode;
using System;
using System.Drawing;
using System.Linq;
Imports IronBarCode

Imports System

Imports System.Drawing

Imports System.Linq
$vbLabelText   $csharpLabel


Create a QR Code with 1 Line of Code

Our first example shows us how to create a standardized barcode with some simple text, a 500-pixel square diameter, with medium error correction.

:path=/static-assets/barcode/content-code-examples/tutorials/csharp-qr-code-generator-1.cs
using IronBarCode;

// Generate a simple QR Code image and save it as a PNG file

// The CreateQrCode method is used to generate a QR Code image.
// Parameters:
// 1. The text that should be encoded in the QR code: "hello world".
// 2. The size of the QR Code: 500 pixels by 500 pixels.
// 3. The error correction level for the QR code: Medium (allows recovery of up to 15% of the data).
// The SaveAsPng method saves the generated QR Code as a PNG file with the specified file name: "MyQR.png".
var qrCode = QRCodeWriter.CreateQrCode("hello world", 500, QRCodeWriter.QrErrorCorrectionLevel.Medium);
qrCode.SaveAsPng("MyQR.png");
Imports IronBarCode



' Generate a simple QR Code image and save it as a PNG file



' The CreateQrCode method is used to generate a QR Code image.

' Parameters:

' 1. The text that should be encoded in the QR code: "hello world".

' 2. The size of the QR Code: 500 pixels by 500 pixels.

' 3. The error correction level for the QR code: Medium (allows recovery of up to 15% of the data).

' The SaveAsPng method saves the generated QR Code as a PNG file with the specified file name: "MyQR.png".

Private qrCode = QRCodeWriter.CreateQrCode("hello world", 500, QRCodeWriter.QrErrorCorrectionLevel.Medium)

qrCode.SaveAsPng("MyQR.png")
$vbLabelText   $csharpLabel

Error correction allows us to define how easy it will be for a QR code to be read in real-world circumstances. Higher error correction levels create larger QR codes with more pixels and more complexity.

C# Create QR Code Image

In the second example, we will look at a use case where a company wishes to add a logo to their QR code, which is something we see commonly these days. By using the QRCodeWriter.CreateQrCodeWithLogo method, in the code sample below, you can see how easy this is.

:path=/static-assets/barcode/content-code-examples/tutorials/csharp-qr-code-generator-2.cs
using IronBarCode;
using IronSoftware.Drawing; // Import IronSoftware.Drawing to use QRCodeLogo class
using System.Drawing;        // Import System.Drawing to access the Color struct

// This example demonstrates how to use the IronBarCode library to generate a QR code,
// customize its appearance, and include a logo for branding purposes.

try
{
    // Load the logo image to embed in the QR code. The file path is given as a string.
    QRCodeLogo qrCodeLogo = new QRCodeLogo("visual-studio-logo.png");

    // Create a QR code with an embedded logo.
    // The URL to encode into the QR code is specified as a parameter to the method.
    GeneratedBarcode myQRCodeWithLogo = QRCodeWriter.CreateQrCodeWithLogo("https://ironsoftware.com/", qrCodeLogo);
    
    // Customize the QR code:
    // - Resize the QR code to 500x500 pixels.
    // - Set its margins to 10 pixels.
    // - Change the QR code color to Dark Green.
    myQRCodeWithLogo.ResizeTo(500, 500).SetMargins(10).ChangeBarCodeColor(System.Drawing.Color.DarkGreen);

    // Save the customized QR Code as a PNG image file.
    // The logo will be automatically sized and positioned appropriately within the QR code grid.
    myQRCodeWithLogo.SaveAsPng("myQRWithLogo.png");
}
catch (Exception ex)
{
    // Handle any exceptions that might occur during QR code creation and saving process.
    Console.WriteLine("An error occurred: " + ex.Message);
}
Imports IronBarCode

Imports IronSoftware.Drawing ' Import IronSoftware.Drawing to use QRCodeLogo class

Imports System.Drawing ' Import System.Drawing to access the Color struct



' This example demonstrates how to use the IronBarCode library to generate a QR code,

' customize its appearance, and include a logo for branding purposes.



Try

	' Load the logo image to embed in the QR code. The file path is given as a string.

	Dim qrCodeLogo As New QRCodeLogo("visual-studio-logo.png")



	' Create a QR code with an embedded logo.

	' The URL to encode into the QR code is specified as a parameter to the method.

	Dim myQRCodeWithLogo As GeneratedBarcode = QRCodeWriter.CreateQrCodeWithLogo("https://ironsoftware.com/", qrCodeLogo)



	' Customize the QR code:

	' - Resize the QR code to 500x500 pixels.

	' - Set its margins to 10 pixels.

	' - Change the QR code color to Dark Green.

	myQRCodeWithLogo.ResizeTo(500, 500).SetMargins(10).ChangeBarCodeColor(System.Drawing.Color.DarkGreen)



	' Save the customized QR Code as a PNG image file.

	' The logo will be automatically sized and positioned appropriately within the QR code grid.

	myQRCodeWithLogo.SaveAsPng("myQRWithLogo.png")

Catch ex As Exception

	' Handle any exceptions that might occur during QR code creation and saving process.

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

End Try
$vbLabelText   $csharpLabel

This example adds the Visual Studio logo to the barcode. It automatically sizes it to an appropriate size where the pure code is still readable and aligns that logo to the QR code's square grid, so that it looks appropriate. The next line of code colors the barcode dark green; however, it does not discolor the logo.

C# Create QR Code With Logo Image

Save as Image, PDF, or HTML

Finally, we save that QR as a PDF. The final line of code opens the PDF in your default PDF browser for your convenience.

:path=/static-assets/barcode/content-code-examples/tutorials/csharp-qr-code-generator-3.cs
using IronBarCode;
using System.Drawing; // Ensure the System.Drawing namespace is included for color definitions

// This script generates a QR code with a logo, modifies its color, and saves it in PDF and HTML formats.

// Create a QRCodeLogo object using a logo image file.
QRCodeLogo qrCodeLogo = new QRCodeLogo("visual-studio-logo.png");

// Generate a QR code with the specified logo and target URL.
GeneratedBarcode myQRCodeWithLogo = QRCodeWriter.CreateQrCodeWithLogo("https://ironsoftware.com/", qrCodeLogo);

// Change the color of the QR code.
myQRCodeWithLogo.ChangeBarCodeColor(Color.DarkGreen);

// Save the generated QR code as a PDF file.
myQRCodeWithLogo.SaveAsPdf("MyQRWithLogo.pdf");

// Save the generated QR code as an HTML file.
myQRCodeWithLogo.SaveAsHtmlFile("MyQRWithLogo.html");
Imports IronBarCode

Imports System.Drawing ' Ensure the System.Drawing namespace is included for color definitions



' This script generates a QR code with a logo, modifies its color, and saves it in PDF and HTML formats.



' Create a QRCodeLogo object using a logo image file.

Private qrCodeLogo As New QRCodeLogo("visual-studio-logo.png")



' Generate a QR code with the specified logo and target URL.

Private myQRCodeWithLogo As GeneratedBarcode = QRCodeWriter.CreateQrCodeWithLogo("https://ironsoftware.com/", qrCodeLogo)



' Change the color of the QR code.

myQRCodeWithLogo.ChangeBarCodeColor(Color.DarkGreen)



' Save the generated QR code as a PDF file.

myQRCodeWithLogo.SaveAsPdf("MyQRWithLogo.pdf")



' Save the generated QR code as an HTML file.

myQRCodeWithLogo.SaveAsHtmlFile("MyQRWithLogo.html")
$vbLabelText   $csharpLabel

Verifying QR Codes

When adding logos to QR codes and changing colors, we want to make sure that our QR is still readable.

By using the GeneratedBarcode.Verify() method, we can test whether or not our barcode is still readable.

In the following code example, we will see that changing a QR code to light blue actually makes it unreadable. We detect this within the code and prefer dark blue.

:path=/static-assets/barcode/content-code-examples/tutorials/csharp-qr-code-generator-4.cs
using IronBarCode;
using IronSoftware.Drawing;
using System;
using System.Drawing; // Added this to resolve Color namespace

// This code demonstrates how to generate a QR code with a logo, verify its readability,
// and save it to an HTML file.
QRCodeLogo qrCodeLogo = new QRCodeLogo("visual-studio-logo.png");

// Generate a QR code with a logo, pointing to a specific URL.
GeneratedBarcode myVerifiedQR = QRCodeWriter.CreateQrCodeWithLogo("https://ironsoftware.com/", qrCodeLogo);

// Change the color of the QR code to LightBlue. This may affect the QR code’s readability.
myVerifiedQR.ChangeBarCodeColor(System.Drawing.Color.LightBlue);

// Verify if the QR code can be read accurately. If not, modify the color to a darker one.
if (!myVerifiedQR.Verify())
{
    Console.WriteLine("\t LightBlue is not dark enough to be read accurately. Let's try DarkBlue");
    myVerifiedQR.ChangeBarCodeColor(System.Drawing.Color.DarkBlue);
}

// Save the QR code as an HTML file.
myVerifiedQR.SaveAsHtmlFile("MyVerifiedQR.html");

// Open the QR code HTML file in the default web browser.
System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo
{
    FileName = "MyVerifiedQR.html",
    UseShellExecute = true // Set to true to use the default application associated with the file type.
});
Imports Microsoft.VisualBasic

Imports IronBarCode

Imports IronSoftware.Drawing

Imports System

Imports System.Drawing ' Added this to resolve Color namespace



' This code demonstrates how to generate a QR code with a logo, verify its readability,

' and save it to an HTML file.

Private qrCodeLogo As New QRCodeLogo("visual-studio-logo.png")



' Generate a QR code with a logo, pointing to a specific URL.

Private myVerifiedQR As GeneratedBarcode = QRCodeWriter.CreateQrCodeWithLogo("https://ironsoftware.com/", qrCodeLogo)



' Change the color of the QR code to LightBlue. This may affect the QR code's readability.

myVerifiedQR.ChangeBarCodeColor(System.Drawing.Color.LightBlue)



' Verify if the QR code can be read accurately. If not, modify the color to a darker one.

If Not myVerifiedQR.Verify() Then

	Console.WriteLine(vbTab & " LightBlue is not dark enough to be read accurately. Let's try DarkBlue")

	myVerifiedQR.ChangeBarCodeColor(System.Drawing.Color.DarkBlue)

End If



' Save the QR code as an HTML file.

myVerifiedQR.SaveAsHtmlFile("MyVerifiedQR.html")



' Open the QR code HTML file in the default web browser.

System.Diagnostics.Process.Start(New System.Diagnostics.ProcessStartInfo With {

	.FileName = "MyVerifiedQR.html",

	.UseShellExecute = True

})
$vbLabelText   $csharpLabel

The final lines of code export the QR code as a standalone HTML file with no assets and then open that HTML file in your default browser.

C# read and write QR

Reading and Writing Binary Data

QR codes are an excellent format for dealing with binary data. Sometimes binary data is simply more space-efficient or more appropriate than dealing with text.

In this example, we will encode some binary data from a string, write that to a barcode in QR format, and then read that back as a bit array of binary data. You will note that this feature is not common to many barcode libraries, making IronBarcode unique in this capacity.

:path=/static-assets/barcode/content-code-examples/tutorials/csharp-qr-code-generator-5.cs
using IronBarCode; // Import the IronBarCode library for QR code generation and reading.
using System; // Import the System namespace for basic functionalities.
using System.Linq; // Import the System.Linq namespace for query capabilities.

// This program demonstrates creating a QR code from binary data, saving it as an image,
// and then reading it back to verify that the data is preserved correctly.

try
{
    // Convert a string to a byte array, representing binary data.
    byte[] binaryData = System.Text.Encoding.UTF8.GetBytes("https://ironsoftware.com/csharp/barcode/");

    // Write a QR code with binary content and save it as an image file.
    // The 'CreateQrCode' method creates a QR code from the provided binary data, and 'SaveAsPng' saves this QR code as a PNG image.
    QRCodeWriter.CreateQrCode(binaryData, 500).SaveAsPng("MyBinaryQR.png");

    // Read the QR code from the saved image and retrieve the binary content.
    // The 'Read' method reads the QR code image, and 'First' retrieves the first result returned.
    var myReturnedData = BarcodeReader.Read("MyBinaryQR.png").First();

    // Compare the original binary data with the data read from the QR code to verify integrity.
    if (binaryData.SequenceEqual(myReturnedData.BinaryValue))
    {
        // If the data matches, print a confirmation message.
        Console.WriteLine("Binary Data Read and Written Perfectly");
    }
    else
    {
        // If the data does not match, throw an exception indicating corrupted data.
        throw new Exception("Corrupted Data");
    }
}
catch (Exception ex)
{
    // Catch any exceptions and print an error message to the console.
    Console.WriteLine($"An error occurred: {ex.Message}");
}
Imports IronBarCode ' Import the IronBarCode library for QR code generation and reading.

Imports System ' Import the System namespace for basic functionalities.

Imports System.Linq ' Import the System.Linq namespace for query capabilities.



' This program demonstrates creating a QR code from binary data, saving it as an image,

' and then reading it back to verify that the data is preserved correctly.



Try

	' Convert a string to a byte array, representing binary data.

	Dim binaryData() As Byte = System.Text.Encoding.UTF8.GetBytes("https://ironsoftware.com/csharp/barcode/")



	' Write a QR code with binary content and save it as an image file.

	' The 'CreateQrCode' method creates a QR code from the provided binary data, and 'SaveAsPng' saves this QR code as a PNG image.

	QRCodeWriter.CreateQrCode(binaryData, 500).SaveAsPng("MyBinaryQR.png")



	' Read the QR code from the saved image and retrieve the binary content.

	' The 'Read' method reads the QR code image, and 'First' retrieves the first result returned.

	Dim myReturnedData = BarcodeReader.Read("MyBinaryQR.png").First()



	' Compare the original binary data with the data read from the QR code to verify integrity.

	If binaryData.SequenceEqual(myReturnedData.BinaryValue) Then

		' If the data matches, print a confirmation message.

		Console.WriteLine("Binary Data Read and Written Perfectly")

	Else

		' If the data does not match, throw an exception indicating corrupted data.

		Throw New Exception("Corrupted Data")

	End If

Catch ex As Exception

	' Catch any exceptions and print an error message to the console.

	Console.WriteLine($"An error occurred: {ex.Message}")

End Try
$vbLabelText   $csharpLabel
C# read and write binary data as a QR Code

In summary, the Barcode C# Library is specifically designed with real-world QR code usage in mind. Not only does it read QR codes quickly and accurately, but it allows us to style them, add logos, verify barcodes, and encode them with binary data.

Reading QR Codes

To save you jumping between tutorials, I will add a code sample for my favorite way to read QR codes using IronBarcode.

:path=/static-assets/barcode/content-code-examples/tutorials/csharp-qr-code-generator-6.cs
// Import necessary namespaces
using IronBarCode;
using System;
using System.Linq;

// Read the QR code image from "QR.png" file.
// The BarcodeReaderOptions specify that we expect QRCode encoding.
BarcodeResults result = BarcodeReader.Read("QR.png", new BarcodeReaderOptions() { 
    ExpectBarcodeTypes = BarcodeEncoding.QRCode 
});

// Check if the result is not null and contains any barcodes.
if (result != null && result.Any())
{
    // Output the value of the first barcode found in the image to the console.
    Console.WriteLine(result.First().Value);
}
else
{
    // If no barcodes are found, output a message indicating so.
    Console.WriteLine("No barcodes found in the image.");
}
' Import necessary namespaces

Imports IronBarCode

Imports System

Imports System.Linq



' Read the QR code image from "QR.png" file.

' The BarcodeReaderOptions specify that we expect QRCode encoding.

Private result As BarcodeResults = BarcodeReader.Read("QR.png", New BarcodeReaderOptions() With {.ExpectBarcodeTypes = BarcodeEncoding.QRCode})



' Check if the result is not null and contains any barcodes.

If result IsNot Nothing AndAlso result.Any() Then

	' Output the value of the first barcode found in the image to the console.

	Console.WriteLine(result.First().Value)

Else

	' If no barcodes are found, output a message indicating so.

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

End If
$vbLabelText   $csharpLabel

A more advanced form also exists with more developer control:

:path=/static-assets/barcode/content-code-examples/tutorials/csharp-qr-code-generator-7.cs
using IronBarCode;
using System;
using System.Linq;

// Configure barcode reading options
BarcodeReaderOptions options = new BarcodeReaderOptions
{
    Speed = ReadingSpeed.Faster, // Set the reading speed to faster
    ExpectMultipleBarcodes = false, // Expect only one barcode in the image
    ExpectBarcodeTypes = BarcodeEncoding.All, // Accept all types of barcode encodings
    Multithreaded = false, // Disable multithreading
    MaxParallelThreads = 1, // Number of parallel threads (should be set to 1 if multithreading is false)
    CropArea = null, // No specific cropping area within the image
    UseCode39ExtendedMode = false, // Do not use extended mode for Code 39 barcodes
    RemoveFalsePositive = false, // Do not apply extra filtering to remove false positives
    ImageFilters = null // No additional image processing filters
};

try
{
    // Read the barcode from the specified image file
    BarcodeResults result = BarcodeReader.Read("QR.png", options);

    // Check if any barcode is detected
    if (result?.Any() == true)
    {
        // Output the value of the first detected barcode
        Console.WriteLine(result.First().Value);
    }
    else
    {
        Console.WriteLine("No barcode detected.");
    }
}
catch (Exception ex)
{
    // Handle any exceptions that occur during barcode reading
    Console.WriteLine($"An error occurred while reading the barcode: {ex.Message}");
}
Imports IronBarCode

Imports System

Imports System.Linq



' Configure barcode reading options

Private options As New BarcodeReaderOptions With {

	.Speed = ReadingSpeed.Faster,

	.ExpectMultipleBarcodes = False,

	.ExpectBarcodeTypes = BarcodeEncoding.All,

	.Multithreaded = False,

	.MaxParallelThreads = 1,

	.CropArea = Nothing,

	.UseCode39ExtendedMode = False,

	.RemoveFalsePositive = False,

	.ImageFilters = Nothing

}



Try

	' Read the barcode from the specified image file

	Dim result As BarcodeResults = BarcodeReader.Read("QR.png", options)



	' Check if any barcode is detected

	If result?.Any() = True Then

		' Output the value of the first detected barcode

		Console.WriteLine(result.First().Value)

	Else

		Console.WriteLine("No barcode detected.")

	End If

Catch ex As Exception

	' Handle any exceptions that occur during barcode reading

	Console.WriteLine($"An error occurred while reading the barcode: {ex.Message}")

End Try
$vbLabelText   $csharpLabel

Moving Forward

To learn more about this example and working with QR codes in C#, we encourage you to fork it on our GitHub page or download the source code from our site.

Source Code Downloads

Download this C# QR Code Generator Tutorial and DLL.

Further Documentation

You may also find the QRCodeWriter and BarcodeReader classes within the API Reference of interest.

They document the full feature set of IronBarcode, a VB.NET Barcode Generator, which could not possibly be packed into a single tutorial.

Frequently Asked Questions

How do I install the QR Code Generator Library in C#?

You can install the QR Code Generator Library in C# by using the NuGet Package Manager to add the BarCode package with the command: dotnet add package BarCode.

What namespaces do I need to import for generating QR codes in C#?

You need to import the IronBarCode namespace along with some standard system assemblies like System, System.Drawing, and System.Linq.

How can I create a basic QR code in C#?

A basic QR code can be created using IronBarCode with a simple line of code: var qrCode = QRCodeWriter.CreateQrCode("Hello, World!", 500, QRCodeWriter.QrErrorCorrection.Medium);

How can I add a logo to a QR code?

You can add a logo to a QR code using the CreateQrCodeWithLogo method provided by IronBarcode, passing the URL, logo file path, size, and error correction level.

What is the process to verify if a QR code is readable after customization?

You can verify if a QR code is readable by using the GeneratedBarcode.Verify() method in IronBarcode, which throws an exception if the QR code is unreadable.

How can I encode binary data into a QR code?

To encode binary data into a QR code, use the QRCodeWriter.CreateQrCode method from IronBarcode with binary data as input, and it will encode the data accordingly.

How do I save a QR code as a PDF or HTML file?

You can save a QR code as a PDF using the SaveAsPdf method in IronBarcode and as a standalone HTML file using the appropriate methods provided by IronBarCode.

What methods are available for reading QR codes?

QR codes can be read using the BarcodeReader.Read method from IronBarcode, which reads from an image file, and advanced options are available using BarcodeReaderOptions for more control.

Can I change the color of a QR code, and how does it affect readability?

Yes, you can change the color of a QR code using the ChangeBackgroundColor method in IronBarcode. However, it's important to verify readability since some colors may render the QR code unreadable.

Where can I find further documentation and source code for QR code generation?

Further documentation and source code for QR code generation can be found in the IronBarcode API Reference and on the GitHub repository linked in the tutorial.

Chaknith Bin
Software Engineer
Chaknith works on IronXL and IronBarcode. He has deep expertise in C# and .NET, helping improve the software and support customers. His insights from user interactions contribute to better products, documentation, and overall experience.