C# QR 码生成器应用程序

This article was translated from English: Does it need improvement?
Translated
View the article in English

欢迎阅读我们的创建指南 QR 码 使用 C#! QR 代码和 .NET 条形码 DLL 已成为快速有效地共享信息的流行方式。无论您是在开发应用程序、管理网站,还是在寻找一种简便的链接共享方式,这些代码都会非常有用。在本指南中,我们将演示如何使用 IronQR确保您可以根据自己的需要生成 QR 代码。该库使任何使用 C# 的人都能轻松创建 QR 代码,而无需进入复杂的逻辑。我们将指导您完成整个步骤,确保您拥有开始使用所需的一切。无论您是想为自己的应用程序添加 QR 代码生成器功能,还是只是想了解它是如何实现的,您都找对了地方。让我们开始吧

在C#中安装QR Code Generator库

适用于的C# NuGet库

安装使用 NuGet

Install-Package IronQR
适用于的C# NuGet库

安装使用 NuGet

Install-Package IronQR
Java PDF JAR

下载 DLL

下载DLL

手动安装到你的项目中

开始在您的项目中使用IronPDF,并立即获取免费试用。

第一步:
green arrow pointer

查看 IronQRNuget 用于快速安装和部署。它有超过800万次下载,正在使用C#改变。

适用于的C# NuGet库 nuget.org/packages/IronQR/
Install-Package IronQR

在开始之前,我们需要安装 IronQR NuGet 软件包。

Install-Package IronQR

IronQR:C# QR 库

IronQR IronQR 是一个 C# QR 码库,用于将 QR 码功能集成到 .NET 应用程序中。IronQR 支持多种 .NET 版本和项目类型,包括 C#、VB.NET、F#、.NET Core、.NET Standard、.NET Framework 等,确保与 Windows、Linux、macOS、iOS 和 Android 等各种开发环境兼容。

IronQR 与众不同之处在于其先进的功能,包括以下能力 读取二维码生成二维码支持多种图像格式,以及调整大小、样式和在 QR 代码中添加徽标等自定义选项。

IronQR 的一些主要功能

除了基本的 QR 代码生成功能外,IronQR 还提供了多项功能,可满足各种 QR 代码相关任务的需要。让我们来了解一下这些功能,并查看它们的示例代码,您可以将这些代码集成到任何类型的 .NET 应用程序模板(如控制台应用程序)中。

读取 QR 码

IronQR 擅长解码 QR 代码,为用户提供了获取 QR 代码中嵌入信息的直接方法。您可以快速、准确地从 QR 码中提取数据,从简单的 URL 到复杂的嵌入信息。

:path=/static-assets/qr/content-code-examples/tutorials/csharp-qr-code-generator-application-1.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
}
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
VB   C#

我们使用以下 QR 进行扫描:

C# 创建 QR 码图像

输出结果是这样的

C# QR 值

这一过程首先要纳入必要的命名空间 IronQr 和 IronSoftware.Drawing,其中特别提到了 IronSoftware.Drawing 命名空间中的 Color,以处理图像处理。

在开始读取二维码之前,必须先将许可证密钥分配给 IronQr.License.LicenseKey,从而激活软件。然后,代码会使用 AnyBitmap.FromFile 从文件中加载二维码图像。("QRCode.png").

加载图像后,下一步就是为二维码检测做准备。准备工作是通过创建 QrImageInput 对象来完成的,该对象是图像的容器。

该功能的核心在于 QrReader 类,它被实例化并用于执行 QR 码读取操作。阅读器会分析准备好的 qrInput 图像,搜索其中包含的任何 QR 代码。该操作的结果是 QrResult 对象的集合,每个对象代表图像中检测到的 QR 代码。

为了访问和使用 QR 代码中编码的数据,代码使用一个 foreach 循环遍历结果集合。每个 QrResult 对象都包含一些属性,如 QR 码的值,这些属性可以被访问和显示。

自定义 QR 读取模式选项

IronQR 为你提供了从图像读取 QR 码的不同方式,使其能满足各种需求。其中一个选项是混合扫描模式,它兼顾了速度和准确性,在二维码不清晰或部分隐藏时非常有用。

另一种是机器学习 (ML) 扫描模式,利用智能技术读取损坏或不易正常读取的 QR 码。该模式非常适合 QR 码难以检测的恶劣环境。

最后是 "基本扫描模式",它是扫描清晰明了的 QR 码最快、最简单的方法。当你需要快速得到结果,而且 QR 码很容易读取时,它是最好的选择。

:path=/static-assets/qr/content-code-examples/tutorials/csharp-qr-code-generator-application-2.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);
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)
VB   C#

读取高级 QR 码

IronQR 的高级 QR 码读取功能旨在为 QR 码扫描和解码提供全面而细致的方法。这套功能超越了基本的 QR 码读取功能,提供了更深层次的互动和数据提取。

:path=/static-assets/qr/content-code-examples/tutorials/csharp-qr-code-generator-application-3.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}");
    }
}
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
VB   C#

这是我们使用 IronQR 扫描二维码时的输出结果:

C# 读取 QR 码结果

我们使用以下二维码:

C# 创建 QR 码图像

每个 QrResult 对象都能访问解码数据 (价值),任何嵌入的 URL (网址)和空间坐标 (积分) 图像中的 QR 码。

对于检测到的每个 QR 码,IronQR 都会提供详细信息,包括 QR 码中包含的确切内容和任何 URL。此外,该库还提供 QR 码在图像中边角的精确坐标 (通过点属性).

要在 C# 应用程序中使用 IronQR QR 代码库创建 QR 代码生成器,请仔细按照以下步骤操作。本指南将带您设置 Windows 窗体应用程序、安装 IronQR 库、编写生成二维码的代码并了解输出结果。

第 1 步:在 Visual Studio 中创建 Windows 应用程序

  • 首先在计算机上启动 Visual Studio。
  • 点击 "创建新项目 "按钮。

  • 选择Windows 窗体应用程序作为项目类型。确保选择 C# 作为语言。
Windows 窗体应用程序

输入项目名称并选择保存位置。然后在下一个屏幕上选择 .NET framework。然后点击创建

项目配置

它将在 Visual Studio 中创建并打开一个 Windows 窗体应用程序。

第 2 步:安装 IronQR 库

现在是在项目中安装 IronQR 库的时候了。你可以通过不同的方法安装 IronQR 库。请根据自己的喜好选择一种:

使用 NuGet 软件包管理器安装

  • 右键单击解决方案资源管理器中的项目,然后选择 Manage NuGet Packages
  • 在搜索框中键入IronQR,然后按Enter
管理 NuGet 软件包

在列表中找到 IronQR,点击旁边的 安装

安装 IronQR

使用 NuGet 软件包管理器控制台安装

转到 工具 > NuGet 软件包管理器 > 软件包管理器控制台

NuGet 软件包管理器

键入 Install-Package IronQR 并按 Enter。

安装 IronQR

步骤 3:设计前台

QR 代码生成器

3.1 标题

生成 QR 码

启动 QR 代码生成器应用程序后,用户会立即看到一个醒目的标题,标题为 "QR Generator IronQR",字体粗体,极具权威性。之所以选用 Agency FB 字体,是因为该字体线条简洁、现代,给人一种高效、精确的感觉。标题字体大小为 48 点,既突出又醒目,既能吸引用户的注意力,又能牢固树立应用程序的形象。

3.2 输入部分

二维码文本输入

QR 码文本输入

输入部分的核心是一个简单而基本的组件:文本输入框。在这里,用户可以输入他们希望编码到二维码中的数据。输入框非常宽敞,可容纳大量文本,并位于顶部附近的显著位置。

徽标选择

选择徽标

在文本输入下方,"选择徽标 "区域允许进行额外的定制。用户可以上传嵌入二维码的徽标,以提高品牌识别度或个性化二维码。相邻的图片框可预览所选徽标,提供即时的视觉反馈。

颜色配置

背景颜色

向右移动,界面会显示颜色选择选项。用户可以通过两个按钮,一个是二维码颜色按钮,另一个是背景颜色按钮,自定义二维码的调色板。这些按钮旁边的丰富文本框显示了当前选择的颜色。

输入部分的文字、徽标和颜色选项布局考虑周到,体现了用户在创建二维码时对优先事项的清晰理解。它将功能性与灵活性相结合,既能让用户快速高效地输入必要信息,又能提供发挥创意的空间。

3.3 造型参数

造型设计

尺寸设置

在颜色定制工具旁边,用户可以找到 "尺寸 "输入。这个数字设置非常重要,因为它决定了二维码的整体尺寸,确保二维码在预定的显示环境中(无论是名片、传单还是数字屏幕)完美匹配。

保证金设置

在尺寸输入旁边,"边距 "字段允许用户指定二维码周围的空白区域。边距不仅是一种美学选择,也是一种功能元素,会影响扫描仪对二维码的可读性。应用程序提供了一个上下数字控件,方便用户调整这一参数。

3.4 输出预览

QR 输出

一旦用户开始生成 QR 码,表单左侧标有 "输出 "的大图片框就会成为焦点。它是一个动态显示屏,可实时预览生成的 QR 代码。这种即时的视觉反馈对于用户在保存之前验证他们的设计选择并确保 QR 代码符合他们的期望至关重要。

3.5 个操作按钮

生成 QR

C# 中的 QR 码

生成 QR "按钮是应用程序界面中的一个关键控制元素。该按钮位于表单的重要位置,是 QR 代码创建过程的催化剂。点击该按钮后,应用程序将接收用户定义的所有输入数据和样式参数,并开始生成自定义 QR 代码。

保存二维码

保存

生成 QR 代码并显示在输出预览区后,"保存 QR "按钮就会发挥作用。点击后,会打开一个保存对话框,允许用户选择所需的文件格式和保存位置。

重置表格

重置

只需单击一下,该按钮即可清除所有先前的输入和选择,将所有设置恢复为默认值。这是表单的一个重要方面,提供了一种无需手动调整每个选项即可重新初始化应用程序的快速方法。

第 4 步:编写后台逻辑

4.1 设置和初始化

首先,应用程序将包含必要的命名空间:IronQr 和 IronSoftware.Drawing。这些命名空间至关重要,因为它们提供了在应用程序中生成和处理 QR 代码和颜色所需的功能。自定义颜色类的定义是为了方便 QR 代码生成中的颜色管理,它覆盖了默认的 System.Drawing.Color,以确保与 IronQR 的要求兼容。

:path=/static-assets/qr/content-code-examples/tutorials/csharp-qr-code-generator-application-4.cs
using IronQr;
using IronSoftware.Drawing;
using Color = IronSoftware.Drawing.Color;


Imports IronQr
Imports IronSoftware.Drawing
Imports Color = IronSoftware.Drawing.Color
VB   C#

QR_Generator 类的构造函数在应用程序的使用准备过程中起着至关重要的作用。在这里,应用程序的组件被初始化,这是 Windows 窗体应用程序中设置窗体 UI 元素的标准步骤。

:path=/static-assets/qr/content-code-examples/tutorials/csharp-qr-code-generator-application-5.cs
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
VB   C#

SetLicenseKey:调用此方法可为 IronQR 库应用有效的许可证密钥。商业应用程序必须使用许可证密钥,才能解锁 IronQR 库的全部功能。

EnsureDirectoryExists:鉴于需要保存生成的 QR 代码,此方法可确保有专门的可用目录。它会检查应用程序启动路径中是否存在 "QR 码 "目录,如果不存在,则创建该目录。

4.2 许可证密钥配置

为确保 IronQR 不受任何限制地运行,必须使用有效的许可证密钥。这是一个静态方法,旨在使用已购买或试用的许可证密钥配置库。下面的代码片段说明了如何设置许可证密钥:

:path=/static-assets/qr/content-code-examples/tutorials/csharp-qr-code-generator-application-6.cs
private static void SetLicenseKey()
{
    IronQr.License.LicenseKey = "YOUR_LICENSE_KEY";
}
Private Shared Sub SetLicenseKey()
	IronQr.License.LicenseKey = "YOUR_LICENSE_KEY"
End Sub
VB   C#

将 "YOUR_LICENSE_KEY "替换为从 Iron Software 获得的实际许可证密钥。该方法在 QR_Generator 类的构造函数中调用,确保应用程序启动后,在生成任何 QR 代码之前,立即应用许可证。

4.3 目录管理

应用程序使用 EnsureDirectoryExists 方法检查用于存储二维码的指定目录是否存在。如果不存在,则创建目录。该方法需要一个字符串参数,即要检查或创建的目录路径。下面是该方法的实现过程:

:path=/static-assets/qr/content-code-examples/tutorials/csharp-qr-code-generator-application-7.cs
private static void EnsureDirectoryExists(string path)
{
    if (!System.IO.Directory.Exists(path))
    {
        System.IO.Directory.CreateDirectory(path);
    }
}
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
VB   C#

该方法利用 System.IO 命名空间与文件系统交互。它首先使用 Directory.Exists 检查指定路径下的目录是否存在。如果目录不存在 (将返回 false)然后使用 Directory.CreateDirectory 创建目录。

QR 代码目录的路径在 QR_Generator 类构造函数中定义为 qrCodesDirectory,它结合了应用程序的启动路径和 "QR 代码 "文件夹名称:

:path=/static-assets/qr/content-code-examples/tutorials/csharp-qr-code-generator-application-8.cs
string qrCodesDirectory = System.IO.Path.Combine(Application.StartupPath, "QR Codes");
Dim qrCodesDirectory As String = System.IO.Path.Combine(Application.StartupPath, "QR Codes")
VB   C#

4.4 颜色选择

应用程序在用户界面上提供了两个按钮,每个按钮都与选择颜色的方法相关联:btn_color_Click 用于选择二维码颜色,btn_background_Click 用于选择背景颜色。这些方法利用颜色对话框让用户选择颜色。

使用颜色对话框选择颜色后,所选颜色将转换为十六进制字符串格式。这是必要的,因为 IronQR 库要求以十六进制格式指定颜色。转换是通过 ColorToHex 方法完成的:

:path=/static-assets/qr/content-code-examples/tutorials/csharp-qr-code-generator-application-9.cs
private string ColorToHex(System.Drawing.Color color)
{
    return $"#{color.R:X2}{color.G:X2}{color.B:X2}";
}
Private Function ColorToHex(ByVal color As System.Drawing.Color) As String
	Return $"#{color.R:X2}{color.G:X2}{color.B:X2}"
End Function
VB   C#

UpdateColor 方法获取所选颜色,并使用十六进制字符串将其转换为 IronSoftware.Drawing.Color 格式,然后根据所选颜色更新二维码的前景色或背景色。它还会更新用户界面,以反映新的颜色选择:

:path=/static-assets/qr/content-code-examples/tutorials/csharp-qr-code-generator-application-10.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;
    }
}
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
VB   C#

4.5 添加徽标

应用程序包含一个按钮 (btn_logo_Click) 点击后会打开一个文件对话框,允许用户选择一个图像文件作为徽标。这一功能对于希望将二维码品牌化的企业或个人来说至关重要。以下是徽标选择和整合过程的处理方式:

:path=/static-assets/qr/content-code-examples/tutorials/csharp-qr-code-generator-application-11.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);
        }
    }
}
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
VB   C#

成功选择图像后,应用程序会尝试加载图像并显示预览。然后,AnyBitmap 对象(logoBmp)将被设置为所选图像,QR 生成逻辑随后将使用该图像。

4.6 QR 码生成

生成过程始于用户点击 "生成 "按钮,该按钮与 btn_generate_Click 方法相关联。该方法充当触发器,调用 GenerateQRCode 函数,实际的生成逻辑就在该函数中。

:path=/static-assets/qr/content-code-examples/tutorials/csharp-qr-code-generator-application-12.cs
private void btn_generate_Click(object sender, EventArgs e)
{
    GenerateQRCode();
}
Private Sub btn_generate_Click(ByVal sender As Object, ByVal e As EventArgs)
	GenerateQRCode()
End Sub
VB   C#

在 GenerateQRCode 方法中,应用程序根据指定的参数(包括输入文本和样式选项)构建 QR 码。该方法封装了 QR 代码的创建过程,应用了所选的颜色、尺寸、边距和可选的徽标。

:path=/static-assets/qr/content-code-examples/tutorials/csharp-qr-code-generator-application-13.cs
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 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
VB   C#

QrOptions 对象可定义纠错级别,增强二维码对损坏或模糊的抵御能力。CreateStyleOptions 方法会生成一个 QrStyleOptions 对象,其中包括用户的自定义设置,如颜色、尺寸和徽标。下面是该方法的详细介绍:

:path=/static-assets/qr/content-code-examples/tutorials/csharp-qr-code-generator-application-14.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
    };
}
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
VB   C#

该方法会创建一个 QrStyleOptions 对象,然后 QR 代码生成逻辑会使用该对象来应用用户的首选项。选项包括

  • BackgroundColor 和 Color:这些属性可设置二维码的背景和前景颜色,从而实现与品牌或审美偏好相匹配的个性化外观。
  • 尺寸:该属性决定了 QR 码的尺寸,使 QR 码可以灵活地适应不同的环境或媒介。
  • 边距:该属性设置二维码周围的边距大小,确保二维码与周围元素隔离,这对可扩展性至关重要。
  • 标识:如果用户选择包含徽标,则可在此处配置徽标的具体尺寸和边角半径,以获得精致的外观。

4.7 保存 QR 码

保存功能由 "保存 "按钮触发,该按钮与 btn_save_Click 方法相关联。该方法调用 SaveQRCode,实现保存逻辑。该过程包括显示保存文件对话框,允许用户选择保存二维码的文件格式和位置。

:path=/static-assets/qr/content-code-examples/tutorials/csharp-qr-code-generator-application-15.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);
        }
    }
}
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
VB   C#

此方法会检查是否有生成的 QR 代码。如果有,它会向用户提供以 PNG 或 JPEG 格式保存文件的选项。DetermineImageFormat 函数可确保根据用户选择的文件扩展名以正确的格式保存图片。

:path=/static-assets/qr/content-code-examples/tutorials/csharp-qr-code-generator-application-16.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;
}
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
VB   C#

这种灵活性使用户可以选择最适合其需求的格式,无论其优先考虑的是质量还是性能。 (巴新) 或文件大小 (JPEG).

4.8 重置应用程序

重置功能与调用 btn_reset_Click 方法的 "重置 "按钮相关联。该方法反过来调用 ResetFields,该函数用于清除所有用户输入,并恢复所有设置的默认值,包括文本字段、颜色选择和所选徽标。

:path=/static-assets/qr/content-code-examples/tutorials/csharp-qr-code-generator-application-17.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;
}
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
VB   C#

此方法可重置 QR 代码生成过程中涉及的每个组件。例如,它会清除二维码文本,将尺寸和边距设置为默认值,并删除任何选定的颜色或徽标。

4.9 错误处理

应用程序使用 ShowError 方法以用户友好的方式显示错误信息。该方法需要两个参数:标题和信息,这两个参数为用户提供了有关错误的上下文。下面是该方法的实现过程:

:path=/static-assets/qr/content-code-examples/tutorials/csharp-qr-code-generator-application-18.cs
private static void ShowError(string title, string message)
{
    MessageBox.Show($"{title}: {message}", "Error");
}
Private Shared Sub ShowError(ByVal title As String, ByVal message As String)
	MessageBox.Show($"{title}: {message}", "Error")
End Sub
VB   C#

该方法适用于应用程序的不同部分,以确保在发生错误时,能以简洁明了的信息及时通知用户。例如,如果在加载徽标或生成二维码的过程中发生错误,应用程序会调用 ShowError 来显示问题的详细信息。

4.10 完整代码示例

下面是完整的代码,可以帮助您更容易地理解代码:

:path=/static-assets/qr/content-code-examples/tutorials/csharp-qr-code-generator-application-19.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");
        }
    }
}
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
VB   C#

第 5 步:运行应用程序

程序运行后,主窗口就会出现,如提供的图片所示。布局整齐地分为输入、样式、输出和操作几个部分。

应用输出

第一步是在 "输入 QR 文本 "字段中输入数据。这些数据将构成 QR 代码的内容,如 URL 或文本信息。接下来,为了个性化 QR 代码,我们需要点击 "选择徽标 "按钮来选择一个徽标。选择后,徽标会明显地显示在按钮旁边的预览框中,确认其已被纳入 QR 代码设计中。

标志

选择徽标后,我们还可以选择 QR 码的前景色和背景色。点击相应按钮后,所选颜色就会在每个按钮旁边的颜色显示框中显示出来,让我们立即直观地确认自己的选择。

颜色选择器

对于这个特定的二维码,我们将尺寸设置为 500,以确保二维码的大小适合我们的需要,并将页边距调整为 20,为二维码提供一个缓冲区,以防止出现扫描问题。

尺寸

设置好所有输入和样式选项后,我们点击 "生成 QR "按钮生成 QR 代码。应用程序会处理我们的输入,并在输出图片框中显示新创建的 QR 代码。

读取 QR 码输出

要保存生成的 QR 代码,我们只需点击 "保存 QR "按钮。该操作会打开一个保存对话框,让我们为二维码图像选择目的地和文件格式。

保存对话框

保存后,会出现一条成功信息,确认 QR 代码已成功存储。

成功信息

如果我们需要重新开始或创建一个新的二维码,点击 "重置表单 "按钮,表单就会恢复到初始状态,清除所有字段和选择,为下一次生成二维码做好准备。

重置表格

这是 IronQR 生成的已保存 QR 代码:

QR 码输出

结论

总之,本指南将引导您在 C# 应用程序中使用 IronQR 库生成 QR 代码。通过分解从在 Visual Studio 中设置项目、集成 IronQR 库、设计用户友好界面到编写后台逻辑的各个步骤,我们展示了在应用程序中添加 QR 码功能是多么容易。

对于那些有兴趣进一步探索 IronQR 功能的人来说,值得注意的是 IronQR 提供了一个 免费试用 即可开始使用。如果您决定将 IronQR 集成到您的项目中,许可证起价为 $749,可为专业级 QR 代码生成提供经济高效的解决方案。