# C# QR Code Generator Application
<div class="alert alert-info iron-variant-1" role="alert">
<a href="/csharp/qr/">IronQR</a> is Iron Software's brand new .NET QR Code library. Leverage modern machine learning techniques to read QR codes from any angle with high accuracy. Generate and customize new QR codes with ease! <a href="/csharp/qr/tutorials/csharp-qr-code-generator/">Get started with IronQR</a> now!
</div>
Welcome to our guide on creating [QR codes](https://en.wikipedia.org/wiki/QR_code) using C#! QR codes and .NET barcode DLL have become popular ways to share information quickly and efficiently. Whether you're developing an app, managing a website, or just looking for a neat way to share links, these codes can be incredibly useful. In this guide, we'll demonstrate how to generate QR codes efficiently using [IronQR](/csharp/qr/), ensuring you can generate QR codes tailored to your needs. This library makes it easy for anyone working with C# to create QR codes without getting into complex logic. We'll walk you through the steps, ensuring you have everything you need to get started. Whether you're looking to add QR code generator functionality to your app or just curious about how it's done, you're in the right place. Let's get started.
<div class="hsg-featured-snippet">
<h2>How to Create a QR Code Generator In C#</h2>
<ol>
<li>Create a Windows Forms Application in Visual Studio</li>
<li><a class="js-modal-open" data-modal-id="trial-license-after-download" href="https://www.nuget.org/packages/IronQR/">Install QR Library using NuGet</a></li>
<li>Design the form frontend elements</li>
<li>Write logic of QR generation</li>
<li>Run the application and start creating QR codes</li>
</ol>
</div>
## Install QR Code Generator Library in C#
!!!--LIBRARY_START_TRIAL_BLOCK--!!!
-----------
Before we start, we need to install the `IronQR` NuGet Package.
```shell
:ProductInstall
```
## IronQR: C# QR Library
[IronQR](/csharp/qr/) is a C# QR Code library for integrating QR code functionality into .NET applications. IronQR supports a wide range of .NET versions and project types, including C#, VB.NET, F#, .NET Core, .NET Standard, .NET Framework, and more, ensuring compatibility with various development environments such as Windows, Linux, macOS, iOS, and Android.
IronQR distinguishes itself with its advanced features, including the ability to [read QR codes](/csharp/qr/examples/read-qr-code/) and [generate QR codes](/csharp/qr/examples/generate-qr-code/), support for multiple image formats, and customization options like resizing, styling, and adding logos to QR codes.
## Some Key Features of IronQR
IronQR extends its functionality beyond basic QR code generation, offering several features designed to accommodate a wide range of QR code-related tasks. Let's go through these features and check their example codes which you will be able to integrate into any type of .NET application template like console app.
### Read QR Codes
IronQR excels in decoding QR codes, providing users with a straightforward way to access the information embedded within QR codes. You can quickly and accurately extract data from QR codes, ranging from simple URLs to complex embedded information.
```cs
using IronQr;
using IronSoftware.Drawing;
using System;
using System.Collections.Generic;
IronQr.License.LicenseKey = "License-Key";
// Load the image file that contains the QR Code
var inputImage = AnyBitmap.FromFile("QRCode.png");
// Prepare the image for QR code detection
QrImageInput qrInput = new QrImageInput(inputImage);
// Initialize the QR Code reader
QrReader qrReader = new QrReader();
// Execute QR Code reading on the provided image
IEnumerable<QrResult> qrResults = qrReader.Read(qrInput);
// Assuming you have the QR results in qrResults as before
foreach (var result in qrResults)
{
Console.WriteLine(result.Value); // Print the QR code content to the console
}
```
The process starts by incorporating the necessary namespaces: `IronQr` and `IronSoftware.Drawing`, with a specific mention of `Color` from the `IronSoftware.Drawing` namespace to handle image manipulations.
Before diving into the QR code reading process, it's essential to activate the software with your license key by assigning it to `IronQr.License.LicenseKey`. The code then proceeds to load the QR code image from a file using `AnyBitmap.FromFile("QRCode.png")`.
With the image loaded, the next step involves preparing it for QR code detection. This preparation is done by creating a `QrImageInput` object, which serves as a container for the image.
The core of this feature lies in the `QrReader` class, which is instantiated and used to perform the QR code reading operation. The reader analyzes the prepared image, searching for any QR codes it contains. The result of this operation is a collection of `QrResult` objects, each representing a detected QR code within the image.
To access and utilize the data encoded in the QR codes, the code iterates over the collection of results using a `foreach` loop. Each `QrResult` object contains properties such as the QR code's value, which can be accessed and displayed.
### Custom QR Read Mode Options
IronQR provides different modes for reading QR codes, making it versatile for various needs.
- **Mixed Scan Mode:** Balances speed and accuracy, useful for QR codes that are not clear or partly hidden.
- **Machine Learning (ML) Scan Mode:** Uses advanced technology to read damaged or hard-to-read QR codes, ideal for difficult-to-detect scenarios.
- **Basic Scan Mode:** The simplest and fastest way, for clear and straightforward QR codes.
```cs
using IronQr;
using IronQr.Enum;
using IronSoftware.Drawing;
using System.Collections.Generic;
IronQr.License.LicenseKey = "License-Key";
// Load the image file that contains the QR Code
var inputImage = AnyBitmap.FromFile("QRCode.png");
QrImageInput mixedScanInput = new QrImageInput(inputImage, QrScanMode.OnlyDetectionModel);
IEnumerable<QrResult> mixedScanResults = new QrReader().Read(mixedScanInput);
QrImageInput mlScanInput = new QrImageInput(inputImage, QrScanMode.OnlyDetectionModel);
IEnumerable<QrResult> mlScanResults = new QrReader().Read(mlScanInput);
QrImageInput basicScanInput = new QrImageInput(inputImage, QrScanMode.OnlyBasicScan);
IEnumerable<QrResult> basicScanResults = new QrReader().Read(basicScanInput);
```
### Read Advanced QR Codes
IronQR's advanced QR code reading capabilities provide a comprehensive approach to QR code scanning and decoding. This feature set goes beyond basic reading, offering a deeper level of interaction and data extraction.
```cs
using IronQr;
using IronSoftware.Drawing;
using System;
using System.Collections.Generic;
IronQr.License.LicenseKey = "License-Key";
var imageToScan = AnyBitmap.FromFile("QRCode.png");
QrImageInput qrInput = new QrImageInput(imageToScan);
QrReader qrScanner = new QrReader();
IEnumerable<QrResult> scanResults = qrScanner.Read(qrInput);
foreach (QrResult qrResult in scanResults)
{
Console.WriteLine(qrResult.Value);
Console.WriteLine(qrResult.Url);
foreach (IronSoftware.Drawing.PointF coordinate in qrResult.Points)
{
Console.WriteLine($"{coordinate.X}, {coordinate.Y}");
}
}
```
To create a QR Code generator using the IronQR library in a C# application, follow these steps carefully. This guide will take you through setting up a Windows form application, installing the IronQR library, writing the code to generate a QR code, and understanding the output.
## Step 1: Create a Windows Application in Visual Studio
1. Start by launching Visual Studio on your computer.
2. Click on the "Create a New Project" button.
3. Select **Windows Forms App** as the project type. Make sure to choose C# as the language.

4. Enter a name for your project and select the location to save it. Then on the next screen, select .NET framework. Then click **Create**.

## Step 2: Install IronQR Library
Now it's time to install the IronQR library in the project. You can install the IronQR library through different methods.
### Install using NuGet Package Manager
1. Right-click on your project in the Solution Explorer and select **Manage NuGet Packages**.
2. Type `IronQR` in the search box and press **Enter**.

3. Find **IronQR** in the list and click **Install** next to it.

### Install using NuGet Package Manager Console
1. Go to **Tools > NuGet Package Manager > Package Manager Console**.
<div class="content-img-align-center">
<img src="/static-assets/qr/tutorials/csharp-qr-code-generator-application/nuget-package-manager.webp" alt="NuGet Package Manager" class="img-responsive add-shadow img-margin" />
</div>
2. Type `Install-Package IronQr` and press Enter.
<div class="content-img-align-center">
<img src="/static-assets/qr/tutorials/csharp-qr-code-generator-application/install-ironqr-via-pm.webp" alt="Install IronQR" class="img-responsive add-shadow img-margin" />
</div>
## Step 3: Design Frontend
<div class="content-img-align-center">
<img src="/static-assets/qr/tutorials/csharp-qr-code-generator-application/qr-code-generator.webp" alt="QR Code Generator" class="img-responsive add-shadow img-margin" />
</div>
### 3.1 Title Header
<div class="content-img-align-center">
<img src="/static-assets/qr/tutorials/csharp-qr-code-generator-application/generate-qr-code.webp" alt="Generate a QR Code" class="img-responsive add-shadow img-margin" />
</div>
Upon launching the QR Code Generator application, users are immediately presented with a striking header titled "QR Generator IronQR," set in a bold and authoritative font.
### 3.2 Input Section
#### Text Input for QR Code
Users can enter the data they wish to encode into their QR code.
#### Logo Selection
<div class="content-img-align-center">
<img src="/static-assets/qr/tutorials/csharp-qr-code-generator-application/select-logo.webp" alt="Select Logo" class="img-responsive add-shadow img-margin" />
</div>
The "Select Logo" area allows for an additional layer of customization. Users can upload a logo that will be embedded in the QR code.
#### Color Configuration
<div class="content-img-align-center">
<img src="/static-assets/qr/tutorials/csharp-qr-code-generator-application/background-color.webp" alt="Background Color" class="img-responsive add-shadow img-margin" />
</div>
Buttons for color selection allow users to customize their QR code's palette.
### 3.3 Styling Parameters
<div class="content-img-align-center">
<img src="/static-assets/qr/tutorials/csharp-qr-code-generator-application/styling.webp" alt="Styling" class="img-responsive add-shadow img-margin" />
</div>
#### Dimension Settings
Allows users to specify the overall size of the QR code.
#### Margin Settings
Allows users to specify the white space surrounding the QR code.
### 3.4 Output Preview
Provides a real-time preview of the generated QR code.
<div class="content-img-align-center">
<img src="/static-assets/qr/tutorials/csharp-qr-code-generator-application/qr-output.webp" alt="QR Output" class="img-responsive add-shadow img-margin" />
</div>
### 3.5 Action Buttons
#### Generate QR
Triggers the QR code creation process.
<div class="content-img-align-center">
<img src="/static-assets/qr/tutorials/csharp-qr-code-generator-application/qr-code-in-csharp.webp" alt="QR Code in C#" class="img-responsive add-shadow img-margin" />
</div>
#### Save QR Code
Opens a save dialog for saving the QR code.
<div class="content-img-align-center">
<img src="/static-assets/qr/tutorials/csharp-qr-code-generator-application/save.webp" alt="Save" class="img-responsive add-shadow img-margin" />
</div>
#### Reset Form
Clears all previous inputs and selections.
<div class="content-img-align-center">
<img src="/static-assets/qr/tutorials/csharp-qr-code-generator-application/reset.webp" alt="Reset" class="img-responsive add-shadow img-margin" />
</div>
## Step 4: Write Backend Logic
### 4.1 Setup and Initialization
Includes necessary namespaces: `IronQr` and `IronSoftware.Drawing`.
```cs
using IronQr;
using IronSoftware.Drawing;
using Color = IronSoftware.Drawing.Color;
```
```cs
public QR_Generator()
{
InitializeComponent();
SetLicenseKey();
EnsureDirectoryExists(qrCodesDirectory);
}
```
### 4.2 License Key Configuration
Applies a valid license key for the IronQR library:
```csharp
private static void SetLicenseKey() {
IronQr.License.LicenseKey = "YOUR_LICENSE_KEY";
}
```
Replace `"YOUR_LICENSE_KEY"` with your actual license key.
### 4.3 Directory Management
Checks or creates necessary directories.
```cs
private static void EnsureDirectoryExists(string path)
{
if (!System.IO.Directory.Exists(path))
{
System.IO.Directory.CreateDirectory(path);
}
}
```
The path to the QR codes directory is defined in the `QR_Generator` class constructor as `qrCodesDirectory`, which combines the application's startup path with a "QR Codes" folder name:
```cs
string qrCodesDirectory = System.IO.Path.Combine(Application.StartupPath, "QR Codes");
```
### 4.4 Color Selection
Provides color dialog components and utility functions.
```cs
private string ColorToHex(System.Drawing.Color color)
{
return $"#{color.R:X2}{color.G:X2}{color.B:X2}";
}
```
The `UpdateColor` method takes the selected color and converts it to the `IronSoftware.Drawing.Color` format using the hexadecimal string, and updates either the QR code's foreground or background color depending on the selection. It also updates the UI to reflect the new color choice:
```cs
private void UpdateColor(ref Color targetColor, Control display, bool isBackground)
{
if (select_color.ShowDialog() == DialogResult.OK)
{
var hexColor = ColorToHex(select_color.Color);
targetColor = new Color(hexColor);
display.BackColor = select_color.Color;
}
}
```
### 4.5 Adding Logo
Allows the user to select a logo.
```cs
private void btn_logo_Click(object sender, EventArgs e)
{
if (select_logo.ShowDialog() == DialogResult.OK)
{
try
{
logoBmp = new AnyBitmap(select_logo.FileName);
selected_logo.Image = Image.FromFile(select_logo.FileName);
}
catch (Exception ex)
{
ShowError("An error occurred while loading the logo", ex.Message);
}
}
}
```
### 4.6 QR Code Generation
Contains logic for generating QR codes based on user inputs.
```cs
private void btn_generate_Click(object sender, EventArgs e)
{
GenerateQRCode();
}
```
The `QrOptions` object defines the error correction level, enhancing the QR code's resilience to damage or obscuration. The `CreateStyleOptions` method generates a `QrStyleOptions` object, which includes the user's custom settings like colors, dimensions, and the logo. Here's the method in detail:
```cs
private QrStyleOptions CreateStyleOptions()
{
return new QrStyleOptions
{
BackgroundColor = bgColor,
Color = color,
Dimensions = txt_dimension.Value > 0 ? Convert.ToInt32(txt_dimension.Value) : throw new ArgumentException("Please select valid dimensions!"),
Margins = Convert.ToInt32(txt_margin.Value),
Logo = logoBmp != null ? new QrLogo { Bitmap = logoBmp, Width = 50, Height = 50, CornerRadius = 5 } : null
};
}
```
### 4.7 Saving the QR Code
Handles saving the generated QR code.
```cs
private void btn_save_Click(object sender, EventArgs e)
{
SaveQRCode();
}
private void SaveQRCode()
{
if (pictureBox.Image == null)
{
MessageBox.Show("There is no QR code to save.", "Error");
return;
}
saveFileDialog.Filter = "PNG Files|*.png|JPEG Files|*.jpg";
saveFileDialog.Title = "Save QR Code";
saveFileDialog.FileName = "QRCode";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
pictureBox.Image.Save(saveFileDialog.FileName, DetermineImageFormat(saveFileDialog.FileName));
MessageBox.Show("QR Code has been saved!", "Success");
}
catch (Exception ex)
{
ShowError("An error occurred while saving the QR code", ex.Message);
}
}
}
```
```cs
private System.Drawing.Imaging.ImageFormat DetermineImageFormat(string filePath)
{
return System.IO.Path.GetExtension(filePath).ToLower() == ".jpg" ? System.Drawing.Imaging.ImageFormat.Jpeg : System.Drawing.Imaging.ImageFormat.Png;
}
```
### 4.8 Resetting the Application
Clears user inputs and resets the form state.
```cs
private void btn_reset_Click(object sender, EventArgs e)
{
ResetFields();
}
private void ResetFields()
{
txt_QR.Text = string.Empty;
txt_dimension.Value = 200;
txt_margin.Value = 0;
bgColor = Color.White;
color = Color.Black;
txt_selected_color.BackColor = System.Drawing.Color.White;
txt_selected_bgcolor.BackColor = System.Drawing.Color.Black;
logoBmp = null;
selected_logo.Image = null;
pictureBox.Image = null;
}
```
### 4.9 Error Handling
Displays error messages to users.
```cs
private static void ShowError(string title, string message)
{
MessageBox.Show($"{title}: {message}", "Error");
}
```
### 4.10 Complete Code Example
The full code combining all the above features can be found in the example file linked to your project.
```cs
using IronQr;
using IronSoftware.Drawing;
using Color = IronSoftware.Drawing.Color;
namespace IronQR_QR_Generator_WinForms
{
public partial class QR_Generator : Form
{
string qrCodesDirectory = System.IO.Path.Combine(Application.StartupPath, "QR Codes");
Color bgColor = Color.White;
Color color = Color.Black;
AnyBitmap? logoBmp = null;
public QR_Generator()
{
InitializeComponent();
SetLicenseKey();
EnsureDirectoryExists(qrCodesDirectory);
}
private static void SetLicenseKey()
{
IronQr.License.LicenseKey = "License-Key";
}
private static void EnsureDirectoryExists(string path)
{
if (!System.IO.Directory.Exists(path))
{
System.IO.Directory.CreateDirectory(path);
}
}
private void btn_color_Click(object sender, EventArgs e)
{
UpdateColor(ref color, txt_selected_color, false);
}
private void btn_background_Click(object sender, EventArgs e)
{
UpdateColor(ref bgColor, txt_selected_bgcolor, true);
}
private string ColorToHex(System.Drawing.Color color)
{
return $"#{color.R:X2}{color.G:X2}{color.B:X2}";
}
private void UpdateColor(ref Color targetColor, Control display, bool isBackground)
{
if (select_color.ShowDialog() == DialogResult.OK)
{
var hexColor = ColorToHex(select_color.Color);
targetColor = new Color(hexColor);
display.BackColor = select_color.Color;
}
}
private void btn_logo_Click(object sender, EventArgs e)
{
if (select_logo.ShowDialog() == DialogResult.OK)
{
try
{
logoBmp = new AnyBitmap(select_logo.FileName);
selected_logo.Image = Image.FromFile(select_logo.FileName);
}
catch (Exception ex)
{
ShowError("An error occurred while loading the logo", ex.Message);
}
}
}
private void btn_generate_Click(object sender, EventArgs e)
{
GenerateQRCode();
}
private void GenerateQRCode()
{
try
{
var options = new QrOptions(QrErrorCorrectionLevel.High);
var myQr = QrWriter.Write(txt_QR.Text, options);
var style = CreateStyleOptions();
var qrImage = myQr.Save(style);
var fileName = $"{DateTime.Now:yyyyMMddHHmmssfff}_QR.png";
var fullPath = System.IO.Path.Combine(qrCodesDirectory, fileName);
qrImage.SaveAs(fullPath);
pictureBox.Image = Image.FromFile(fullPath);
}
catch (Exception ex)
{
ShowError("An error occurred during QR code generation or saving", ex.Message);
}
}
private QrStyleOptions CreateStyleOptions()
{
return new QrStyleOptions
{
BackgroundColor = bgColor,
Color = color,
Dimensions = txt_dimension.Value > 0 ? Convert.ToInt32(txt_dimension.Value) : throw new ArgumentException("Please select valid dimensions!"),
Margins = Convert.ToInt32(txt_margin.Value),
Logo = logoBmp != null ? new QrLogo { Bitmap = logoBmp, Width = 50, Height = 50, CornerRadius = 5 } : null
};
}
private void btn_save_Click(object sender, EventArgs e)
{
SaveQRCode();
}
private void SaveQRCode()
{
if (pictureBox.Image == null)
{
MessageBox.Show("There is no QR code to save.", "Error");
return;
}
saveFileDialog.Filter = "PNG Files|*.png|JPEG Files|*.jpg";
saveFileDialog.Title = "Save QR Code";
saveFileDialog.FileName = "QRCode";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
pictureBox.Image.Save(saveFileDialog.FileName, DetermineImageFormat(saveFileDialog.FileName));
MessageBox.Show("QR Code has been saved!", "Success");
}
catch (Exception ex)
{
ShowError("An error occurred while saving the QR code", ex.Message);
}
}
}
private System.Drawing.Imaging.ImageFormat DetermineImageFormat(string filePath)
{
return System.IO.Path.GetExtension(filePath).ToLower() == ".jpg" ? System.Drawing.Imaging.ImageFormat.Jpeg : System.Drawing.Imaging.ImageFormat.Png;
}
private void btn_reset_Click(object sender, EventArgs e)
{
ResetFields();
}
private void ResetFields()
{
txt_QR.Text = string.Empty;
txt_dimension.Value = 200;
txt_margin.Value = 0;
bgColor = Color.White;
color = Color.Black;
txt_selected_color.BackColor = bgColor;
txt_selected_bgcolor.BackColor = color;
logoBmp = null;
selected_logo.Image = null;
pictureBox.Image = null;
}
private static void ShowError(string title, string message)
{
MessageBox.Show($"{title}: {message}", "Error");
}
}
}
```
## Step 5: Run Application
When the application is executed, the main window appears as organized with sections for input, styling, output, and actions. Follow the user interface to enter data, customize your QR code, and generate and save the QR code as desired.
## Conclusion
In conclusion, this guide has walked you through the process of generating QR codes using the IronQR library in a C# application. By breaking down the steps from setting up your project in Visual Studio, integrating the IronQR library, designing a user-friendly interface, and writing the backend logic, we've demonstrated how accessible it is to add QR code functionality to your applications.
For those interested in exploring the capabilities of IronQR further, note that IronQR offers a <a class='js-modal-open' data-modal-id='trial-license'>free trial</a> to get you started. Should you decide to integrate IronQR into your projects, licenses start at `$liteLicense`, providing a cost-effective solution for professional-grade QR code generation.
IronQR is Iron Software's brand new .NET QR Code library. Leverage modern machine learning techniques to read QR codes from any angle with high accuracy. Generate and customize new QR codes with ease! Get started with IronQR now!
Welcome to our guide on creating QR codes using C#! QR codes and .NET barcode DLL have become popular ways to share information quickly and efficiently. Whether you're developing an app, managing a website, or just looking for a neat way to share links, these codes can be incredibly useful. In this guide, we'll demonstrate how to generate QR codes efficiently using IronQR, ensuring you can generate QR codes tailored to your needs. This library makes it easy for anyone working with C# to create QR codes without getting into complex logic. We'll walk you through the steps, ensuring you have everything you need to get started. Whether you're looking to add QR code generator functionality to your app or just curious about how it's done, you're in the right place. Let's get started.
How to Create a QR Code Generator In C#
Create a Windows Forms Application in Visual Studio
Start using IronQR in your project today with a free trial.
First Step:
Before we start, we need to install the IronQR NuGet Package.
PM > Install-Package IronQR
Install-Package IronQR
IronQR: C# QR Library
IronQR is a C# QR Code library for integrating QR code functionality into .NET applications. IronQR supports a wide range of .NET versions and project types, including C#, VB.NET, F#, .NET Core, .NET Standard, .NET Framework, and more, ensuring compatibility with various development environments such as Windows, Linux, macOS, iOS, and Android.
IronQR distinguishes itself with its advanced features, including the ability to read QR codes and generate QR codes, support for multiple image formats, and customization options like resizing, styling, and adding logos to QR codes.
Some Key Features of IronQR
IronQR extends its functionality beyond basic QR code generation, offering several features designed to accommodate a wide range of QR code-related tasks. Let's go through these features and check their example codes which you will be able to integrate into any type of .NET application template like console app.
Read QR Codes
IronQR excels in decoding QR codes, providing users with a straightforward way to access the information embedded within QR codes. You can quickly and accurately extract data from QR codes, ranging from simple URLs to complex embedded information.
using IronQr;using IronSoftware.Drawing;using System;using System.Collections.Generic;IronQr.License.LicenseKey = "License-Key";// Load the image file that contains the QR Codevar inputImage = AnyBitmap.FromFile("QRCode.png");// Prepare the image for QR code detectionQrImageInput qrInput = new QrImageInput(inputImage);// Initialize the QR Code readerQrReader qrReader = new QrReader();// Execute QR Code reading on the provided imageIEnumerable<QrResult> qrResults = qrReader.Read(qrInput);// Assuming you have the QR results in qrResults as beforeforeach (var result in qrResults){Console.WriteLine(result.Value); // Print the QR code content to the console}
using IronQr;
using IronSoftware.Drawing;
using System;
using System.Collections.Generic;
IronQr.License.LicenseKey = "License-Key";
// Load the image file that contains the QR Code
var inputImage = AnyBitmap.FromFile("QRCode.png");
// Prepare the image for QR code detection
QrImageInput qrInput = new QrImageInput(inputImage);
// Initialize the QR Code reader
QrReader qrReader = new QrReader();
// Execute QR Code reading on the provided image
IEnumerable<QrResult> qrResults = qrReader.Read(qrInput);
// Assuming you have the QR results in qrResults as before
foreach (var result in qrResults)
{
Console.WriteLine(result.Value); // Print the QR code content to the console
}
ImportsIronQrImportsIronSoftware.DrawingImportsSystemImportsSystem.Collections.GenericIronQr.License.LicenseKey = "License-Key"' Load the image file that contains the QR CodeDim inputImage = AnyBitmap.FromFile("QRCode.png")' Prepare the image for QR code detectionDim qrInput As New QrImageInput(inputImage)' Initialize the QR Code readerDim qrReader As New QrReader()' Execute QR Code reading on the provided imageDim qrResults AsIEnumerable(OfQrResult) = qrReader.Read(qrInput)' Assuming you have the QR results in qrResults as beforeFor Each result In qrResultsConsole.WriteLine(result.Value) ' Print the QR code content to the consoleNext result
Imports IronQr
Imports IronSoftware.Drawing
Imports System
Imports System.Collections.Generic
IronQr.License.LicenseKey = "License-Key"
' Load the image file that contains the QR Code
Dim inputImage = AnyBitmap.FromFile("QRCode.png")
' Prepare the image for QR code detection
Dim qrInput As New QrImageInput(inputImage)
' Initialize the QR Code reader
Dim qrReader As New QrReader()
' Execute QR Code reading on the provided image
Dim qrResults As IEnumerable(Of QrResult) = qrReader.Read(qrInput)
' Assuming you have the QR results in qrResults as before
For Each result In qrResults
Console.WriteLine(result.Value) ' Print the QR code content to the console
Next result
The process starts by incorporating the necessary namespaces: IronQr and IronSoftware.Drawing, with a specific mention of Color from the IronSoftware.Drawing namespace to handle image manipulations.
Before diving into the QR code reading process, it's essential to activate the software with your license key by assigning it to IronQr.License.LicenseKey. The code then proceeds to load the QR code image from a file using AnyBitmap.FromFile("QRCode.png").
With the image loaded, the next step involves preparing it for QR code detection. This preparation is done by creating a QrImageInput object, which serves as a container for the image.
The core of this feature lies in the QrReader class, which is instantiated and used to perform the QR code reading operation. The reader analyzes the prepared image, searching for any QR codes it contains. The result of this operation is a collection of QrResult objects, each representing a detected QR code within the image.
To access and utilize the data encoded in the QR codes, the code iterates over the collection of results using a foreach loop. Each QrResult object contains properties such as the QR code's value, which can be accessed and displayed.
Custom QR Read Mode Options
IronQR provides different modes for reading QR codes, making it versatile for various needs.
Mixed Scan Mode: Balances speed and accuracy, useful for QR codes that are not clear or partly hidden.
Machine Learning (ML) Scan Mode: Uses advanced technology to read damaged or hard-to-read QR codes, ideal for difficult-to-detect scenarios.
Basic Scan Mode: The simplest and fastest way, for clear and straightforward QR codes.
using IronQr;using IronQr.Enum;using IronSoftware.Drawing;using System.Collections.Generic;IronQr.License.LicenseKey = "License-Key";// Load the image file that contains the QR Codevar inputImage = AnyBitmap.FromFile("QRCode.png");QrImageInput mixedScanInput = new QrImageInput(inputImage, QrScanMode.OnlyDetectionModel);IEnumerable<QrResult> mixedScanResults = new QrReader().Read(mixedScanInput);QrImageInput mlScanInput = new QrImageInput(inputImage, QrScanMode.OnlyDetectionModel);IEnumerable<QrResult> mlScanResults = new QrReader().Read(mlScanInput);QrImageInput basicScanInput = new QrImageInput(inputImage, QrScanMode.OnlyBasicScan);IEnumerable<QrResult> basicScanResults = new QrReader().Read(basicScanInput);
using IronQr;
using IronQr.Enum;
using IronSoftware.Drawing;
using System.Collections.Generic;
IronQr.License.LicenseKey = "License-Key";
// Load the image file that contains the QR Code
var inputImage = AnyBitmap.FromFile("QRCode.png");
QrImageInput mixedScanInput = new QrImageInput(inputImage, QrScanMode.OnlyDetectionModel);
IEnumerable<QrResult> mixedScanResults = new QrReader().Read(mixedScanInput);
QrImageInput mlScanInput = new QrImageInput(inputImage, QrScanMode.OnlyDetectionModel);
IEnumerable<QrResult> mlScanResults = new QrReader().Read(mlScanInput);
QrImageInput basicScanInput = new QrImageInput(inputImage, QrScanMode.OnlyBasicScan);
IEnumerable<QrResult> basicScanResults = new QrReader().Read(basicScanInput);
ImportsIronQrImportsIronQr.EnumImportsIronSoftware.DrawingImportsSystem.Collections.GenericIronQr.License.LicenseKey = "License-Key"' Load the image file that contains the QR CodeDim inputImage = AnyBitmap.FromFile("QRCode.png")Dim mixedScanInput As New QrImageInput(inputImage, QrScanMode.OnlyDetectionModel)Dim mixedScanResults AsIEnumerable(OfQrResult) = (New QrReader()).Read(mixedScanInput)Dim mlScanInput As New QrImageInput(inputImage, QrScanMode.OnlyDetectionModel)Dim mlScanResults AsIEnumerable(OfQrResult) = (New QrReader()).Read(mlScanInput)Dim basicScanInput As New QrImageInput(inputImage, QrScanMode.OnlyBasicScan)Dim basicScanResults AsIEnumerable(OfQrResult) = (New QrReader()).Read(basicScanInput)
Imports IronQr
Imports IronQr.Enum
Imports IronSoftware.Drawing
Imports System.Collections.Generic
IronQr.License.LicenseKey = "License-Key"
' Load the image file that contains the QR Code
Dim inputImage = AnyBitmap.FromFile("QRCode.png")
Dim mixedScanInput As New QrImageInput(inputImage, QrScanMode.OnlyDetectionModel)
Dim mixedScanResults As IEnumerable(Of QrResult) = (New QrReader()).Read(mixedScanInput)
Dim mlScanInput As New QrImageInput(inputImage, QrScanMode.OnlyDetectionModel)
Dim mlScanResults As IEnumerable(Of QrResult) = (New QrReader()).Read(mlScanInput)
Dim basicScanInput As New QrImageInput(inputImage, QrScanMode.OnlyBasicScan)
Dim basicScanResults As IEnumerable(Of QrResult) = (New QrReader()).Read(basicScanInput)
Read Advanced QR Codes
IronQR's advanced QR code reading capabilities provide a comprehensive approach to QR code scanning and decoding. This feature set goes beyond basic reading, offering a deeper level of interaction and data extraction.
using IronQr;using IronSoftware.Drawing;using System;using System.Collections.Generic;IronQr.License.LicenseKey = "License-Key";var imageToScan = AnyBitmap.FromFile("QRCode.png");QrImageInput qrInput = new QrImageInput(imageToScan);QrReader qrScanner = new QrReader();IEnumerable<QrResult> scanResults = qrScanner.Read(qrInput);foreach (QrResult qrResult in scanResults){Console.WriteLine(qrResult.Value);Console.WriteLine(qrResult.Url); foreach (IronSoftware.Drawing.PointF coordinate in qrResult.Points) {Console.WriteLine($"{coordinate.X}, {coordinate.Y}"); }}
using IronQr;
using IronSoftware.Drawing;
using System;
using System.Collections.Generic;
IronQr.License.LicenseKey = "License-Key";
var imageToScan = AnyBitmap.FromFile("QRCode.png");
QrImageInput qrInput = new QrImageInput(imageToScan);
QrReader qrScanner = new QrReader();
IEnumerable<QrResult> scanResults = qrScanner.Read(qrInput);
foreach (QrResult qrResult in scanResults)
{
Console.WriteLine(qrResult.Value);
Console.WriteLine(qrResult.Url);
foreach (IronSoftware.Drawing.PointF coordinate in qrResult.Points)
{
Console.WriteLine($"{coordinate.X}, {coordinate.Y}");
}
}
ImportsIronQrImportsIronSoftware.DrawingImportsSystemImportsSystem.Collections.GenericIronQr.License.LicenseKey = "License-Key"Dim imageToScan = AnyBitmap.FromFile("QRCode.png")Dim qrInput As New QrImageInput(imageToScan)Dim qrScanner As New QrReader()Dim scanResults AsIEnumerable(OfQrResult) = qrScanner.Read(qrInput)For Each qrResult AsQrResultIn scanResultsConsole.WriteLine(qrResult.Value)Console.WriteLine(qrResult.Url) For Each coordinate AsIronSoftware.Drawing.PointFIn qrResult.PointsConsole.WriteLine($"{coordinate.X}, {coordinate.Y}") Next coordinateNext qrResult
Imports IronQr
Imports IronSoftware.Drawing
Imports System
Imports System.Collections.Generic
IronQr.License.LicenseKey = "License-Key"
Dim imageToScan = AnyBitmap.FromFile("QRCode.png")
Dim qrInput As New QrImageInput(imageToScan)
Dim qrScanner As New QrReader()
Dim scanResults As IEnumerable(Of QrResult) = qrScanner.Read(qrInput)
For Each qrResult As QrResult In scanResults
Console.WriteLine(qrResult.Value)
Console.WriteLine(qrResult.Url)
For Each coordinate As IronSoftware.Drawing.PointF In qrResult.Points
Console.WriteLine($"{coordinate.X}, {coordinate.Y}")
Next coordinate
Next qrResult
To create a QR Code generator using the IronQR library in a C# application, follow these steps carefully. This guide will take you through setting up a Windows form application, installing the IronQR library, writing the code to generate a QR code, and understanding the output.
Step 1: Create a Windows Application in Visual Studio
Start by launching Visual Studio on your computer.
Click on the "Create a New Project" button.
Select Windows Forms App as the project type. Make sure to choose C# as the language.
Enter a name for your project and select the location to save it. Then on the next screen, select .NET framework. Then click Create.
Step 2: Install IronQR Library
Now it's time to install the IronQR library in the project. You can install the IronQR library through different methods.
Install using NuGet Package Manager
Right-click on your project in the Solution Explorer and select Manage NuGet Packages.
Type IronQR in the search box and press Enter.
Find IronQR in the list and click Install next to it.
Install using NuGet Package Manager Console
Go to Tools > NuGet Package Manager > Package Manager Console.
Type Install-Package IronQr and press Enter.
Step 3: Design Frontend
3.1 Title Header
Upon launching the QR Code Generator application, users are immediately presented with a striking header titled "QR Generator IronQR," set in a bold and authoritative font.
3.2 Input Section
Text Input for QR Code
Users can enter the data they wish to encode into their QR code.
Logo Selection
The "Select Logo" area allows for an additional layer of customization. Users can upload a logo that will be embedded in the QR code.
Color Configuration
Buttons for color selection allow users to customize their QR code's palette.
3.3 Styling Parameters
Dimension Settings
Allows users to specify the overall size of the QR code.
Margin Settings
Allows users to specify the white space surrounding the QR code.
3.4 Output Preview
Provides a real-time preview of the generated QR code.
3.5 Action Buttons
Generate QR
Triggers the QR code creation process.
Save QR Code
Opens a save dialog for saving the QR code.
Reset Form
Clears all previous inputs and selections.
Step 4: Write Backend Logic
4.1 Setup and Initialization
Includes necessary namespaces: IronQr and IronSoftware.Drawing.
using IronQr;using IronSoftware.Drawing;using Color = IronSoftware.Drawing.Color;
using IronQr;
using IronSoftware.Drawing;
using Color = IronSoftware.Drawing.Color;
public QR_Generator()
{
InitializeComponent();
SetLicenseKey();
EnsureDirectoryExists(qrCodesDirectory);
}
'INSTANT VB WARNING: The following constructor is declared outside of its associated class:'ORIGINAL LINE: public QR_Generator()Public Sub New()InitializeComponent()SetLicenseKey()EnsureDirectoryExists(qrCodesDirectory)End Sub
'INSTANT VB WARNING: The following constructor is declared outside of its associated class:
'ORIGINAL LINE: public QR_Generator()
Public Sub New()
InitializeComponent()
SetLicenseKey()
EnsureDirectoryExists(qrCodesDirectory)
End Sub
4.2 License Key Configuration
Applies a valid license key for the IronQR library:
PrivateShared Sub EnsureDirectoryExists(ByVal path AsString) IfNotSystem.IO.Directory.Exists(path) ThenSystem.IO.Directory.CreateDirectory(path) End IfEnd Sub
Private Shared Sub EnsureDirectoryExists(ByVal path As String)
If Not System.IO.Directory.Exists(path) Then
System.IO.Directory.CreateDirectory(path)
End If
End Sub
The path to the QR codes directory is defined in the QR_Generator class constructor as qrCodesDirectory, which combines the application's startup path with a "QR Codes" folder name:
Private Function ColorToHex(ByVal color AsSystem.Drawing.Color) AsString Return $"#{color.R:X2}{color.G:X2}{color.B:X2}"End Function
Private Function ColorToHex(ByVal color As System.Drawing.Color) As String
Return $"#{color.R:X2}{color.G:X2}{color.B:X2}"
End Function
The UpdateColor method takes the selected color and converts it to the IronSoftware.Drawing.Color format using the hexadecimal string, and updates either the QR code's foreground or background color depending on the selection. It also updates the UI to reflect the new color choice:
private voidUpdateColor(ref Color targetColor, Control display, bool isBackground){ if (select_color.ShowDialog() == DialogResult.OK) { var hexColor = ColorToHex(select_color.Color); targetColor = new Color(hexColor); display.BackColor = select_color.Color; }}
private void UpdateColor(ref Color targetColor, Control display, bool isBackground)
{
if (select_color.ShowDialog() == DialogResult.OK)
{
var hexColor = ColorToHex(select_color.Color);
targetColor = new Color(hexColor);
display.BackColor = select_color.Color;
}
}
Private Sub UpdateColor(ByRef targetColor AsColor, ByVal display AsControl, ByVal isBackground AsBoolean) If select_color.ShowDialog() = DialogResult.OKThen Dim hexColor = ColorToHex(select_color.Color) targetColor = New Color(hexColor) display.BackColor = select_color.Color End IfEnd Sub
Private Sub UpdateColor(ByRef targetColor As Color, ByVal display As Control, ByVal isBackground As Boolean)
If select_color.ShowDialog() = DialogResult.OK Then
Dim hexColor = ColorToHex(select_color.Color)
targetColor = New Color(hexColor)
display.BackColor = select_color.Color
End If
End Sub
4.5 Adding Logo
Allows the user to select a logo.
private void btn_logo_Click(object sender, EventArgs e){ if (select_logo.ShowDialog() == DialogResult.OK) { try { logoBmp = new AnyBitmap(select_logo.FileName); selected_logo.Image = Image.FromFile(select_logo.FileName); } catch (Exception ex) {ShowError("An error occurred while loading the logo", ex.Message); } }}
private void btn_logo_Click(object sender, EventArgs e)
{
if (select_logo.ShowDialog() == DialogResult.OK)
{
try
{
logoBmp = new AnyBitmap(select_logo.FileName);
selected_logo.Image = Image.FromFile(select_logo.FileName);
}
catch (Exception ex)
{
ShowError("An error occurred while loading the logo", ex.Message);
}
}
}
Private Sub btn_logo_Click(ByVal sender AsObject, ByVal e AsEventArgs) If select_logo.ShowDialog() = DialogResult.OKThenTry logoBmp = New AnyBitmap(select_logo.FileName) selected_logo.Image = Image.FromFile(select_logo.FileName)Catch ex AsExceptionShowError("An error occurred while loading the logo", ex.Message)EndTry End IfEnd Sub
Private Sub btn_logo_Click(ByVal sender As Object, ByVal e As EventArgs)
If select_logo.ShowDialog() = DialogResult.OK Then
Try
logoBmp = New AnyBitmap(select_logo.FileName)
selected_logo.Image = Image.FromFile(select_logo.FileName)
Catch ex As Exception
ShowError("An error occurred while loading the logo", ex.Message)
End Try
End If
End Sub
4.6 QR Code Generation
Contains logic for generating QR codes based on user inputs.
Private Sub btn_generate_Click(ByVal sender AsObject, ByVal e AsEventArgs)GenerateQRCode()End Sub
Private Sub btn_generate_Click(ByVal sender As Object, ByVal e As EventArgs)
GenerateQRCode()
End Sub
The QrOptions object defines the error correction level, enhancing the QR code's resilience to damage or obscuration. The CreateStyleOptions method generates a QrStyleOptions object, which includes the user's custom settings like colors, dimensions, and the logo. Here's the method in detail:
Private Function CreateStyleOptions() AsQrStyleOptions'INSTANT VB TODO TASK: Throw expressions are not converted by Instant VB:'ORIGINAL LINE: return new QrStyleOptions { BackgroundColor = bgColor, Color = color, Dimensions = txt_dimension.Value > 0 ? Convert.ToInt32(txt_dimension.Value) : throw new ArgumentException("Please select valid dimensions!"), Margins = Convert.ToInt32(txt_margin.Value), Logo = logoBmp != null ? new QrLogo { Bitmap = logoBmp, Width = 50, Height = 50, CornerRadius = 5 } : null }; Return New QrStyleOptionsWith { .BackgroundColor = bgColor, .Color = color, .Dimensions = If(txt_dimension.Value > 0, Convert.ToInt32(txt_dimension.Value), throw New ArgumentException("Please select valid dimensions!")), .Margins = Convert.ToInt32(txt_margin.Value), .Logo = If(logoBmp IsNot Nothing, New QrLogoWith { .Bitmap = logoBmp, .Width = 50, .Height = 50, .CornerRadius = 5 }, Nothing) }End Function
Private Function CreateStyleOptions() As QrStyleOptions
'INSTANT VB TODO TASK: Throw expressions are not converted by Instant VB:
'ORIGINAL LINE: return new QrStyleOptions { BackgroundColor = bgColor, Color = color, Dimensions = txt_dimension.Value > 0 ? Convert.ToInt32(txt_dimension.Value) : throw new ArgumentException("Please select valid dimensions!"), Margins = Convert.ToInt32(txt_margin.Value), Logo = logoBmp != null ? new QrLogo { Bitmap = logoBmp, Width = 50, Height = 50, CornerRadius = 5 } : null };
Return New QrStyleOptions With {
.BackgroundColor = bgColor,
.Color = color,
.Dimensions = If(txt_dimension.Value > 0, Convert.ToInt32(txt_dimension.Value), throw New ArgumentException("Please select valid dimensions!")),
.Margins = Convert.ToInt32(txt_margin.Value),
.Logo = If(logoBmp IsNot Nothing, New QrLogo With {
.Bitmap = logoBmp,
.Width = 50,
.Height = 50,
.CornerRadius = 5
}, Nothing)
}
End Function
4.7 Saving the QR Code
Handles saving the generated QR code.
private void btn_save_Click(object sender, EventArgs e){SaveQRCode();}private voidSaveQRCode(){ if (pictureBox.Image == null) {MessageBox.Show("There is no QR code to save.", "Error"); return; } saveFileDialog.Filter = "PNG Files|*.png|JPEG Files|*.jpg"; saveFileDialog.Title = "Save QR Code"; saveFileDialog.FileName = "QRCode"; if (saveFileDialog.ShowDialog() == DialogResult.OK) { try { pictureBox.Image.Save(saveFileDialog.FileName, DetermineImageFormat(saveFileDialog.FileName));MessageBox.Show("QR Code has been saved!", "Success"); } catch (Exception ex) {ShowError("An error occurred while saving the QR code", ex.Message); } }}
private void btn_save_Click(object sender, EventArgs e)
{
SaveQRCode();
}
private void SaveQRCode()
{
if (pictureBox.Image == null)
{
MessageBox.Show("There is no QR code to save.", "Error");
return;
}
saveFileDialog.Filter = "PNG Files|*.png|JPEG Files|*.jpg";
saveFileDialog.Title = "Save QR Code";
saveFileDialog.FileName = "QRCode";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
pictureBox.Image.Save(saveFileDialog.FileName, DetermineImageFormat(saveFileDialog.FileName));
MessageBox.Show("QR Code has been saved!", "Success");
}
catch (Exception ex)
{
ShowError("An error occurred while saving the QR code", ex.Message);
}
}
}
Private Sub btn_save_Click(ByVal sender AsObject, ByVal e AsEventArgs)SaveQRCode()End SubPrivate Sub SaveQRCode() If pictureBox.ImageIs Nothing ThenMessageBox.Show("There is no QR code to save.", "Error") Return End If saveFileDialog.Filter = "PNG Files|*.png|JPEG Files|*.jpg" saveFileDialog.Title = "Save QR Code" saveFileDialog.FileName = "QRCode" If saveFileDialog.ShowDialog() = DialogResult.OKThenTry pictureBox.Image.Save(saveFileDialog.FileName, DetermineImageFormat(saveFileDialog.FileName))MessageBox.Show("QR Code has been saved!", "Success")Catch ex AsExceptionShowError("An error occurred while saving the QR code", ex.Message)EndTry End IfEnd Sub
Private Sub btn_save_Click(ByVal sender As Object, ByVal e As EventArgs)
SaveQRCode()
End Sub
Private Sub SaveQRCode()
If pictureBox.Image Is Nothing Then
MessageBox.Show("There is no QR code to save.", "Error")
Return
End If
saveFileDialog.Filter = "PNG Files|*.png|JPEG Files|*.jpg"
saveFileDialog.Title = "Save QR Code"
saveFileDialog.FileName = "QRCode"
If saveFileDialog.ShowDialog() = DialogResult.OK Then
Try
pictureBox.Image.Save(saveFileDialog.FileName, DetermineImageFormat(saveFileDialog.FileName))
MessageBox.Show("QR Code has been saved!", "Success")
Catch ex As Exception
ShowError("An error occurred while saving the QR code", ex.Message)
End Try
End If
End Sub
Private Function DetermineImageFormat(ByVal filePath AsString) AsSystem.Drawing.Imaging.ImageFormat Return If(System.IO.Path.GetExtension(filePath).ToLower() = ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg, System.Drawing.Imaging.ImageFormat.Png)End Function
Private Function DetermineImageFormat(ByVal filePath As String) As System.Drawing.Imaging.ImageFormat
Return If(System.IO.Path.GetExtension(filePath).ToLower() = ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg, System.Drawing.Imaging.ImageFormat.Png)
End Function
Private Sub btn_reset_Click(ByVal sender AsObject, ByVal e AsEventArgs)ResetFields()End SubPrivate Sub ResetFields() txt_QR.Text = String.Empty txt_dimension.Value = 200 txt_margin.Value = 0 bgColor = Color.White color = Color.Black txt_selected_color.BackColor = System.Drawing.Color.White txt_selected_bgcolor.BackColor = System.Drawing.Color.Black logoBmp = Nothing selected_logo.Image = Nothing pictureBox.Image = NothingEnd Sub
Private Sub btn_reset_Click(ByVal sender As Object, ByVal e As EventArgs)
ResetFields()
End Sub
Private Sub ResetFields()
txt_QR.Text = String.Empty
txt_dimension.Value = 200
txt_margin.Value = 0
bgColor = Color.White
color = Color.Black
txt_selected_color.BackColor = System.Drawing.Color.White
txt_selected_bgcolor.BackColor = System.Drawing.Color.Black
logoBmp = Nothing
selected_logo.Image = Nothing
pictureBox.Image = Nothing
End Sub
PrivateShared Sub ShowError(ByVal title AsString, ByVal message AsString)MessageBox.Show($"{title}: {message}", "Error")End Sub
Private Shared Sub ShowError(ByVal title As String, ByVal message As String)
MessageBox.Show($"{title}: {message}", "Error")
End Sub
4.10 Complete Code Example
The full code combining all the above features can be found in the example file linked to your project.
using IronQr;using IronSoftware.Drawing;using Color = IronSoftware.Drawing.Color;namespace IronQR_QR_Generator_WinForms{ public partial class QR_Generator : Form { string qrCodesDirectory = System.IO.Path.Combine(Application.StartupPath, "QR Codes"); Color bgColor = Color.White; Color color = Color.Black; AnyBitmap? logoBmp = null; publicQR_Generator() {InitializeComponent();SetLicenseKey();EnsureDirectoryExists(qrCodesDirectory); } private static voidSetLicenseKey() {IronQr.License.LicenseKey = "License-Key"; } private static voidEnsureDirectoryExists(string path) { if (!System.IO.Directory.Exists(path)) {System.IO.Directory.CreateDirectory(path); } } private void btn_color_Click(object sender, EventArgs e) {UpdateColor(ref color, txt_selected_color, false); } private void btn_background_Click(object sender, EventArgs e) {UpdateColor(ref bgColor, txt_selected_bgcolor, true); } private stringColorToHex(System.Drawing.Color color) { return $"#{color.R:X2}{color.G:X2}{color.B:X2}"; } private voidUpdateColor(ref Color targetColor, Control display, bool isBackground) { if (select_color.ShowDialog() == DialogResult.OK) { var hexColor = ColorToHex(select_color.Color); targetColor = new Color(hexColor); display.BackColor = select_color.Color; } } private void btn_logo_Click(object sender, EventArgs e) { if (select_logo.ShowDialog() == DialogResult.OK) { try { logoBmp = new AnyBitmap(select_logo.FileName); selected_logo.Image = Image.FromFile(select_logo.FileName); } catch (Exception ex) {ShowError("An error occurred while loading the logo", ex.Message); } } } private void btn_generate_Click(object sender, EventArgs e) {GenerateQRCode(); } private voidGenerateQRCode() { try { var options = new QrOptions(QrErrorCorrectionLevel.High); var myQr = QrWriter.Write(txt_QR.Text, options); var style = CreateStyleOptions(); var qrImage = myQr.Save(style); var fileName = $"{DateTime.Now:yyyyMMddHHmmssfff}_QR.png"; var fullPath = System.IO.Path.Combine(qrCodesDirectory, fileName); qrImage.SaveAs(fullPath); pictureBox.Image = Image.FromFile(fullPath); } catch (Exception ex) {ShowError("An error occurred during QR code generation or saving", ex.Message); } } private QrStyleOptionsCreateStyleOptions() { return new QrStyleOptions {BackgroundColor = bgColor,Color = color,Dimensions = txt_dimension.Value > 0 ? Convert.ToInt32(txt_dimension.Value) : throw new ArgumentException("Please select valid dimensions!"),Margins = Convert.ToInt32(txt_margin.Value),Logo = logoBmp != null ? new QrLogo { Bitmap = logoBmp, Width = 50, Height = 50, CornerRadius = 5 } : null }; } private void btn_save_Click(object sender, EventArgs e) {SaveQRCode(); } private voidSaveQRCode() { if (pictureBox.Image == null) {MessageBox.Show("There is no QR code to save.", "Error"); return; } saveFileDialog.Filter = "PNG Files|*.png|JPEG Files|*.jpg"; saveFileDialog.Title = "Save QR Code"; saveFileDialog.FileName = "QRCode"; if (saveFileDialog.ShowDialog() == DialogResult.OK) { try { pictureBox.Image.Save(saveFileDialog.FileName, DetermineImageFormat(saveFileDialog.FileName));MessageBox.Show("QR Code has been saved!", "Success"); } catch (Exception ex) {ShowError("An error occurred while saving the QR code", ex.Message); } } } private System.Drawing.Imaging.ImageFormatDetermineImageFormat(string filePath) { returnSystem.IO.Path.GetExtension(filePath).ToLower() == ".jpg" ? System.Drawing.Imaging.ImageFormat.Jpeg : System.Drawing.Imaging.ImageFormat.Png; } private void btn_reset_Click(object sender, EventArgs e) {ResetFields(); } private voidResetFields() { txt_QR.Text = string.Empty; txt_dimension.Value = 200; txt_margin.Value = 0; bgColor = Color.White; color = Color.Black; txt_selected_color.BackColor = bgColor; txt_selected_bgcolor.BackColor = color; logoBmp = null; selected_logo.Image = null; pictureBox.Image = null; } private static voidShowError(string title, string message) {MessageBox.Show($"{title}: {message}", "Error"); } }}
using IronQr;
using IronSoftware.Drawing;
using Color = IronSoftware.Drawing.Color;
namespace IronQR_QR_Generator_WinForms
{
public partial class QR_Generator : Form
{
string qrCodesDirectory = System.IO.Path.Combine(Application.StartupPath, "QR Codes");
Color bgColor = Color.White;
Color color = Color.Black;
AnyBitmap? logoBmp = null;
public QR_Generator()
{
InitializeComponent();
SetLicenseKey();
EnsureDirectoryExists(qrCodesDirectory);
}
private static void SetLicenseKey()
{
IronQr.License.LicenseKey = "License-Key";
}
private static void EnsureDirectoryExists(string path)
{
if (!System.IO.Directory.Exists(path))
{
System.IO.Directory.CreateDirectory(path);
}
}
private void btn_color_Click(object sender, EventArgs e)
{
UpdateColor(ref color, txt_selected_color, false);
}
private void btn_background_Click(object sender, EventArgs e)
{
UpdateColor(ref bgColor, txt_selected_bgcolor, true);
}
private string ColorToHex(System.Drawing.Color color)
{
return $"#{color.R:X2}{color.G:X2}{color.B:X2}";
}
private void UpdateColor(ref Color targetColor, Control display, bool isBackground)
{
if (select_color.ShowDialog() == DialogResult.OK)
{
var hexColor = ColorToHex(select_color.Color);
targetColor = new Color(hexColor);
display.BackColor = select_color.Color;
}
}
private void btn_logo_Click(object sender, EventArgs e)
{
if (select_logo.ShowDialog() == DialogResult.OK)
{
try
{
logoBmp = new AnyBitmap(select_logo.FileName);
selected_logo.Image = Image.FromFile(select_logo.FileName);
}
catch (Exception ex)
{
ShowError("An error occurred while loading the logo", ex.Message);
}
}
}
private void btn_generate_Click(object sender, EventArgs e)
{
GenerateQRCode();
}
private void GenerateQRCode()
{
try
{
var options = new QrOptions(QrErrorCorrectionLevel.High);
var myQr = QrWriter.Write(txt_QR.Text, options);
var style = CreateStyleOptions();
var qrImage = myQr.Save(style);
var fileName = $"{DateTime.Now:yyyyMMddHHmmssfff}_QR.png";
var fullPath = System.IO.Path.Combine(qrCodesDirectory, fileName);
qrImage.SaveAs(fullPath);
pictureBox.Image = Image.FromFile(fullPath);
}
catch (Exception ex)
{
ShowError("An error occurred during QR code generation or saving", ex.Message);
}
}
private QrStyleOptions CreateStyleOptions()
{
return new QrStyleOptions
{
BackgroundColor = bgColor,
Color = color,
Dimensions = txt_dimension.Value > 0 ? Convert.ToInt32(txt_dimension.Value) : throw new ArgumentException("Please select valid dimensions!"),
Margins = Convert.ToInt32(txt_margin.Value),
Logo = logoBmp != null ? new QrLogo { Bitmap = logoBmp, Width = 50, Height = 50, CornerRadius = 5 } : null
};
}
private void btn_save_Click(object sender, EventArgs e)
{
SaveQRCode();
}
private void SaveQRCode()
{
if (pictureBox.Image == null)
{
MessageBox.Show("There is no QR code to save.", "Error");
return;
}
saveFileDialog.Filter = "PNG Files|*.png|JPEG Files|*.jpg";
saveFileDialog.Title = "Save QR Code";
saveFileDialog.FileName = "QRCode";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
pictureBox.Image.Save(saveFileDialog.FileName, DetermineImageFormat(saveFileDialog.FileName));
MessageBox.Show("QR Code has been saved!", "Success");
}
catch (Exception ex)
{
ShowError("An error occurred while saving the QR code", ex.Message);
}
}
}
private System.Drawing.Imaging.ImageFormat DetermineImageFormat(string filePath)
{
return System.IO.Path.GetExtension(filePath).ToLower() == ".jpg" ? System.Drawing.Imaging.ImageFormat.Jpeg : System.Drawing.Imaging.ImageFormat.Png;
}
private void btn_reset_Click(object sender, EventArgs e)
{
ResetFields();
}
private void ResetFields()
{
txt_QR.Text = string.Empty;
txt_dimension.Value = 200;
txt_margin.Value = 0;
bgColor = Color.White;
color = Color.Black;
txt_selected_color.BackColor = bgColor;
txt_selected_bgcolor.BackColor = color;
logoBmp = null;
selected_logo.Image = null;
pictureBox.Image = null;
}
private static void ShowError(string title, string message)
{
MessageBox.Show($"{title}: {message}", "Error");
}
}
}
ImportsIronQrImportsIronSoftware.DrawingImportsColor = IronSoftware.Drawing.ColorNamespaceIronQR_QR_Generator_WinFormsPartialPublic Class QR_GeneratorInheritsForm Private qrCodesDirectory AsString = System.IO.Path.Combine(Application.StartupPath, "QR Codes") Private bgColor AsColor = Color.White Private color AsColor = Color.Black Private logoBmp? AsAnyBitmap = Nothing Public Sub New()InitializeComponent()SetLicenseKey()EnsureDirectoryExists(qrCodesDirectory) End Sub PrivateShared Sub SetLicenseKey()IronQr.License.LicenseKey = "License-Key" End Sub PrivateShared Sub EnsureDirectoryExists(ByVal path AsString) IfNotSystem.IO.Directory.Exists(path) ThenSystem.IO.Directory.CreateDirectory(path) End If End Sub Private Sub btn_color_Click(ByVal sender AsObject, ByVal e AsEventArgs)UpdateColor(color, txt_selected_color, False) End Sub Private Sub btn_background_Click(ByVal sender AsObject, ByVal e AsEventArgs)UpdateColor(bgColor, txt_selected_bgcolor, True) End Sub Private Function ColorToHex(ByVal color AsSystem.Drawing.Color) AsString Return $"#{color.R:X2}{color.G:X2}{color.B:X2}" End Function Private Sub UpdateColor(ByRef targetColor AsColor, ByVal display AsControl, ByVal isBackground AsBoolean) If select_color.ShowDialog() = System.Windows.Forms.DialogResult.OKThen Dim hexColor = ColorToHex(select_color.Color) targetColor = New Color(hexColor) display.BackColor = select_color.Color End If End Sub Private Sub btn_logo_Click(ByVal sender AsObject, ByVal e AsEventArgs) If select_logo.ShowDialog() = System.Windows.Forms.DialogResult.OKThenTry logoBmp = New AnyBitmap(select_logo.FileName) selected_logo.Image = Image.FromFile(select_logo.FileName)Catch ex AsExceptionShowError("An error occurred while loading the logo", ex.Message)EndTry End If End Sub Private Sub btn_generate_Click(ByVal sender AsObject, ByVal e AsEventArgs)GenerateQRCode() End Sub Private Sub GenerateQRCode()Try Dim options = New QrOptions(QrErrorCorrectionLevel.High) Dim myQr = QrWriter.Write(txt_QR.Text, options) Dim style = CreateStyleOptions() Dim qrImage = myQr.Save(style) Dim fileName = $"{DateTime.Now:yyyyMMddHHmmssfff}_QR.png" Dim fullPath = System.IO.Path.Combine(qrCodesDirectory, fileName) qrImage.SaveAs(fullPath) pictureBox.Image = Image.FromFile(fullPath)Catch ex AsExceptionShowError("An error occurred during QR code generation or saving", ex.Message)EndTry End Sub Private Function CreateStyleOptions() AsQrStyleOptions'INSTANT VB TODO TASK: Throw expressions are not converted by Instant VB:'ORIGINAL LINE: return new QrStyleOptions { BackgroundColor = bgColor, Color = color, Dimensions = txt_dimension.Value > 0 ? Convert.ToInt32(txt_dimension.Value) : throw new ArgumentException("Please select valid dimensions!"), Margins = Convert.ToInt32(txt_margin.Value), Logo = logoBmp != null ? new QrLogo { Bitmap = logoBmp, Width = 50, Height = 50, CornerRadius = 5 } : null }; Return New QrStyleOptionsWith { .BackgroundColor = bgColor, .Color = color, .Dimensions = If(txt_dimension.Value > 0, Convert.ToInt32(txt_dimension.Value), throw New ArgumentException("Please select valid dimensions!")), .Margins = Convert.ToInt32(txt_margin.Value), .Logo = If(logoBmp IsNot Nothing, New QrLogoWith { .Bitmap = logoBmp, .Width = 50, .Height = 50, .CornerRadius = 5 }, Nothing) } End Function Private Sub btn_save_Click(ByVal sender AsObject, ByVal e AsEventArgs)SaveQRCode() End Sub Private Sub SaveQRCode() If pictureBox.ImageIs Nothing ThenMessageBox.Show("There is no QR code to save.", "Error") Return End If saveFileDialog.Filter = "PNG Files|*.png|JPEG Files|*.jpg" saveFileDialog.Title = "Save QR Code" saveFileDialog.FileName = "QRCode" If saveFileDialog.ShowDialog() = System.Windows.Forms.DialogResult.OKThenTry pictureBox.Image.Save(saveFileDialog.FileName, DetermineImageFormat(saveFileDialog.FileName))MessageBox.Show("QR Code has been saved!", "Success")Catch ex AsExceptionShowError("An error occurred while saving the QR code", ex.Message)EndTry End If End Sub Private Function DetermineImageFormat(ByVal filePath AsString) AsSystem.Drawing.Imaging.ImageFormat Return If(System.IO.Path.GetExtension(filePath).ToLower() = ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg, System.Drawing.Imaging.ImageFormat.Png) End Function Private Sub btn_reset_Click(ByVal sender AsObject, ByVal e AsEventArgs)ResetFields() End Sub Private Sub ResetFields() txt_QR.Text = String.Empty txt_dimension.Value = 200 txt_margin.Value = 0 bgColor = Color.White color = Color.Black txt_selected_color.BackColor = bgColor txt_selected_bgcolor.BackColor = color logoBmp = Nothing selected_logo.Image = Nothing pictureBox.Image = Nothing End Sub PrivateShared Sub ShowError(ByVal title AsString, ByVal message AsString)MessageBox.Show($"{title}: {message}", "Error") End Sub End ClassEndNamespace
Imports IronQr
Imports IronSoftware.Drawing
Imports Color = IronSoftware.Drawing.Color
Namespace IronQR_QR_Generator_WinForms
Partial Public Class QR_Generator
Inherits Form
Private qrCodesDirectory As String = System.IO.Path.Combine(Application.StartupPath, "QR Codes")
Private bgColor As Color = Color.White
Private color As Color = Color.Black
Private logoBmp? As AnyBitmap = Nothing
Public Sub New()
InitializeComponent()
SetLicenseKey()
EnsureDirectoryExists(qrCodesDirectory)
End Sub
Private Shared Sub SetLicenseKey()
IronQr.License.LicenseKey = "License-Key"
End Sub
Private Shared Sub EnsureDirectoryExists(ByVal path As String)
If Not System.IO.Directory.Exists(path) Then
System.IO.Directory.CreateDirectory(path)
End If
End Sub
Private Sub btn_color_Click(ByVal sender As Object, ByVal e As EventArgs)
UpdateColor(color, txt_selected_color, False)
End Sub
Private Sub btn_background_Click(ByVal sender As Object, ByVal e As EventArgs)
UpdateColor(bgColor, txt_selected_bgcolor, True)
End Sub
Private Function ColorToHex(ByVal color As System.Drawing.Color) As String
Return $"#{color.R:X2}{color.G:X2}{color.B:X2}"
End Function
Private Sub UpdateColor(ByRef targetColor As Color, ByVal display As Control, ByVal isBackground As Boolean)
If select_color.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
Dim hexColor = ColorToHex(select_color.Color)
targetColor = New Color(hexColor)
display.BackColor = select_color.Color
End If
End Sub
Private Sub btn_logo_Click(ByVal sender As Object, ByVal e As EventArgs)
If select_logo.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
Try
logoBmp = New AnyBitmap(select_logo.FileName)
selected_logo.Image = Image.FromFile(select_logo.FileName)
Catch ex As Exception
ShowError("An error occurred while loading the logo", ex.Message)
End Try
End If
End Sub
Private Sub btn_generate_Click(ByVal sender As Object, ByVal e As EventArgs)
GenerateQRCode()
End Sub
Private Sub GenerateQRCode()
Try
Dim options = New QrOptions(QrErrorCorrectionLevel.High)
Dim myQr = QrWriter.Write(txt_QR.Text, options)
Dim style = CreateStyleOptions()
Dim qrImage = myQr.Save(style)
Dim fileName = $"{DateTime.Now:yyyyMMddHHmmssfff}_QR.png"
Dim fullPath = System.IO.Path.Combine(qrCodesDirectory, fileName)
qrImage.SaveAs(fullPath)
pictureBox.Image = Image.FromFile(fullPath)
Catch ex As Exception
ShowError("An error occurred during QR code generation or saving", ex.Message)
End Try
End Sub
Private Function CreateStyleOptions() As QrStyleOptions
'INSTANT VB TODO TASK: Throw expressions are not converted by Instant VB:
'ORIGINAL LINE: return new QrStyleOptions { BackgroundColor = bgColor, Color = color, Dimensions = txt_dimension.Value > 0 ? Convert.ToInt32(txt_dimension.Value) : throw new ArgumentException("Please select valid dimensions!"), Margins = Convert.ToInt32(txt_margin.Value), Logo = logoBmp != null ? new QrLogo { Bitmap = logoBmp, Width = 50, Height = 50, CornerRadius = 5 } : null };
Return New QrStyleOptions With {
.BackgroundColor = bgColor,
.Color = color,
.Dimensions = If(txt_dimension.Value > 0, Convert.ToInt32(txt_dimension.Value), throw New ArgumentException("Please select valid dimensions!")),
.Margins = Convert.ToInt32(txt_margin.Value),
.Logo = If(logoBmp IsNot Nothing, New QrLogo With {
.Bitmap = logoBmp,
.Width = 50,
.Height = 50,
.CornerRadius = 5
}, Nothing)
}
End Function
Private Sub btn_save_Click(ByVal sender As Object, ByVal e As EventArgs)
SaveQRCode()
End Sub
Private Sub SaveQRCode()
If pictureBox.Image Is Nothing Then
MessageBox.Show("There is no QR code to save.", "Error")
Return
End If
saveFileDialog.Filter = "PNG Files|*.png|JPEG Files|*.jpg"
saveFileDialog.Title = "Save QR Code"
saveFileDialog.FileName = "QRCode"
If saveFileDialog.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
Try
pictureBox.Image.Save(saveFileDialog.FileName, DetermineImageFormat(saveFileDialog.FileName))
MessageBox.Show("QR Code has been saved!", "Success")
Catch ex As Exception
ShowError("An error occurred while saving the QR code", ex.Message)
End Try
End If
End Sub
Private Function DetermineImageFormat(ByVal filePath As String) As System.Drawing.Imaging.ImageFormat
Return If(System.IO.Path.GetExtension(filePath).ToLower() = ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg, System.Drawing.Imaging.ImageFormat.Png)
End Function
Private Sub btn_reset_Click(ByVal sender As Object, ByVal e As EventArgs)
ResetFields()
End Sub
Private Sub ResetFields()
txt_QR.Text = String.Empty
txt_dimension.Value = 200
txt_margin.Value = 0
bgColor = Color.White
color = Color.Black
txt_selected_color.BackColor = bgColor
txt_selected_bgcolor.BackColor = color
logoBmp = Nothing
selected_logo.Image = Nothing
pictureBox.Image = Nothing
End Sub
Private Shared Sub ShowError(ByVal title As String, ByVal message As String)
MessageBox.Show($"{title}: {message}", "Error")
End Sub
End Class
End Namespace
Step 5: Run Application
When the application is executed, the main window appears as organized with sections for input, styling, output, and actions. Follow the user interface to enter data, customize your QR code, and generate and save the QR code as desired.
Conclusion
In conclusion, this guide has walked you through the process of generating QR codes using the IronQR library in a C# application. By breaking down the steps from setting up your project in Visual Studio, integrating the IronQR library, designing a user-friendly interface, and writing the backend logic, we've demonstrated how accessible it is to add QR code functionality to your applications.
For those interested in exploring the capabilities of IronQR further, note that IronQR offers a free trial to get you started. Should you decide to integrate IronQR into your projects, licenses start at $999, providing a cost-effective solution for professional-grade QR code generation.
Frequently Asked Questions
What is IronQR?
IronQR is Iron Software's .NET QR Code library. It integrates QR code functionality into .NET applications, supports various .NET versions, and offers features like QR code reading, generation, and customization.
How do I install IronQR in my C# project?
You can install IronQR through the NuGet Package Manager by searching for 'IronQR' and clicking Install, or via the NuGet Package Manager Console by entering 'Install-Package IronQR'.
What steps are involved in creating a QR code generator in C# using IronQR?
To create a QR code generator, start by creating a Windows Forms Application in Visual Studio, install IronQR, design the UI, write logic for QR code generation, and finally run your application to generate QR codes.
Can I customize QR codes generated with IronQR?
Yes, IronQR allows you to customize QR codes by setting parameters such as dimensions, margins, colors, and adding logos for personalized QR code design.
What is the role of a license key in IronQR?
A license key is required to activate IronQR library features. Set the license key in your application code to enable full functionality of the QR code generation and reading.
What are the different scan modes available in IronQR?
IronQR offers Mixed Scan Mode, Machine Learning Scan Mode, and Basic Scan Mode to balance speed, accuracy, and handle various QR code conditions, including damaged or difficult-to-read codes.
How does IronQR handle QR code reading?
IronQR provides an easy way to read QR codes by loading an image, preparing it for detection, and using a QrReader to analyze and extract embedded data effectively.
Is IronQR compatible with different development environments?
Yes, IronQR supports a wide range of .NET project types and is compatible with various environments like Windows, Linux, macOS, iOS, and Android.
What is the suggested way to handle errors when using IronQR?
It's recommended to implement error handling in your application to catch exceptions that may occur during QR code generation or reading, ensuring a smooth experience.
Can I run the QR code generator application on different platforms?
Yes, with IronQR's compatibility across various .NET frameworks, you can run the QR code generator application on multiple platforms like Windows, Linux, and macOS.
Curtis Chau holds a Bachelor’s degree in Computer Science (Carleton University) and specializes in front-end development with expertise in Node.js, TypeScript, JavaScript, and React. Passionate about crafting intuitive and aesthetically pleasing user interfaces, Curtis enjoys working with modern frameworks and creating well-structured, visually appealing manuals.