C# QR 码生成器应用程序

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

欢迎阅读我们的创建指南QR 码使用 C#! QR 码和 .NET 条形码 DLL 已成为快速高效分享信息的流行方式。 无论您是在开发一个应用程序、管理一个网站还是寻找一种整洁的方式来分享链接,这些代码都非常有用。 在本指南中,我们将演示如何使用 IronQR 高效生成二维码。IronQR确保您可以生成符合您需求的QR码。 这个库使得任何使用C#的人都能轻松创建二维码,无需涉及复杂逻辑。 我们将指导您完成步骤,确保您拥有开始所需的一切。 无论您是希望在您的应用程序中添加二维码生成功能,还是仅仅对其实现方式感兴趣,您都来对地方了。 让我们开始吧。

在C#中安装QR码生成库

立即在您的项目中开始使用IronQR,并享受免费试用。

第一步:
green arrow pointer


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

Install-Package IronQR

IronQR: C# QR 库

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

IronQR 以其先进功能而著称,包括能够读取二维码生成二维码支持多种图像格式,以及调整大小、样式和在 QR 代码中添加徽标等自定义选项。

IronQR的一些关键特性

IronQR扩展了其功能,不仅仅是基本的QR码生成,还提供了多种功能,以适应广泛的QR码相关任务。 让我们了解这些功能并查看其示例代码,您将能够将其集成到任何类型的 .NET 应用程序模板中,例如控制台应用。

读取二维码

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,以处理图像操作。

在深入了解QR码阅读过程之前,必须通过将许可证密钥分配给IronQR.License.LicenseKey来激活软件。 代码接着使用 AnyBitmap.FromFile 从文件中加载 QR 码图像。("QRCode.png").

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

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

要访问和使用二维码中编码的数据,代码使用 foreach 循环遍历结果集合。每个 QrResult 对象包含诸如二维码的值之类的属性,可以访问并显示这些属性。

自定义 QR 读取模式选项

IronQR为您提供了从图像中读取QR码的不同方式,使其适用于各种需求。 一种选择是混合扫描模式,它平衡了速度和准确性,当二维码不清晰或部分隐藏时很有用。

另一个是机器学习(ML)扫描模式,使用智能技术读取受损或难以正常识别的二维码。 此模式非常适用于难以识别 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码,IronQR提供详细信息,包括QR码内的确切内容和任何包含的网址。 此外,该库提供了图像中QR码角落的精确坐标。(通过点属性).

要在 C# 应用程序中使用 IronQR 库创建 QR 码生成器,请仔细遵循以下步骤。 本指南将引导您完成设置 Windows 窗体应用程序、安装 IronQR 库、编写生成 QR 码的代码以及理解输出的过程。

步骤1:在Visual Studio中创建一个Windows应用程序

  • 首先在您的计算机上启动Visual Studio。
  • 点击“创建新项目”按钮。
  • 选择 Windows Forms App 作为项目类型。 确保选择C#作为编程语言。
    Windows 窗体应用程序

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

    项目配置

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

步骤2:安装 IronQR 库

现在是时候在项目中安装IronQR库了。 您可以通过不同的方法安装 IronQR 库。 请选择一个符合您的偏好:

使用 NuGet 包管理器安装

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

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

    安装 IronQR

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

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

NuGet 软件包管理器

键入 Install-Package IronQR 并按 Enter。

安装 IronQR

步骤 3:设计前台

QR 代码生成器

3.1 标题

生成 QR 码

启动QR码生成器应用程序后,用户会立即看到一个标题为“QR生成器 IronQR”的醒目标题,采用了粗体和权威的字体。 所选字体Agency FB以其清晰、现代的线条而著称,传达了一种效率和精确性的感觉。 字体大小为48号的标题既突出又有力,能够吸引用户的注意力,并牢牢确立应用程序的身份。

3.2 输入部分

二维码文本输入

QR 码文本输入

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

徽标选择

选择徽标

在文本输入框下方的“选择徽标”区域允许进行额外的定制层。 用户可以上传一个标志,该标志将嵌入到二维码中,增强品牌识别或个性化代码。 相邻的图片框提供了所选标志的预览,提供即时的视觉反馈。

颜色配置

背景颜色

向右移动,界面提供了颜色选择的选项。 两个按钮,一个用于设置QR码的颜色,另一个用于设置背景颜色,使用户可以自定义他们的QR码的配色方案。 这些按钮旁边的富文本框显示了当前选择的颜色。

输入部分的周到布局,包括其文本、标志和颜色选项,反映出在创建QR码时对用户优先级的清晰理解。 它将功能性与灵活性相结合,使用户能够快速高效地输入所需信息,同时也提供了发挥创造力的空间。

3.3 造型参数

造型设计

维度设置

在颜色自定义工具旁边,用户会发现“尺寸”输入。这一数值设置至关重要,因为它决定了二维码的整体大小,确保它能完美地适应预定的显示场合,无论是名片、传单还是数字屏幕。

边距设置

在尺寸输入旁边的“边距”字段允许用户指定二维码周围的白色空间。 边距不仅仅是审美选择;它们是可以影响扫描器读取QR码的功能性元素。 该应用程序为用户提供了一个数字上下控制,以便轻松调整此参数。

3.4 输出预览

QR 输出

一旦用户启动QR码生成,表单左侧的大图片框,标记为“输出”,便成为焦点。 它充当动态显示器,提供生成的二维码的实时预览。 此即时视觉反馈对于用户来说至关重要,可用于验证设计选择并确保二维码符合他们的期望,然后再进行保存。

3.5 个操作按钮

生成 QR

C# 中的 QR 码

"生成QR"按钮是应用程序界面中的一个关键控制元素。 位于表单中的策略位置,这个按钮是生成二维码过程的催化剂。 点击此按钮后,应用程序将采用用户定义的所有输入数据和样式参数,开始生成自定义QR码。

保存二维码

保存

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

重置表格

重置

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

第 4 步:编写后台逻辑

4.1 设置和初始化

首先,应用程序从包含必要的命名空间开始:IronQR 和 IronSoftware.Drawing。 这些命名空间是必不可少的,因为它们提供了在应用程序中生成和操作QR码和颜色所需的功能。 自定义 Color 类被定义用于在 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 Forms应用程序中设置表单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库的全部功能。

确保目录存在:鉴于需要保存生成的QR码,此方法确保有一个专用的目录可用。 它检查应用程序启动路径是否存在“QR Codes”目录,如果不存在则创建它。

4.2 许可证密钥配置

要确保 IronQR 操作无限制,必须应用有效的许可证密钥。 这是通过 SetLicenseKey 方法来实现的,这是一个用于将库配置为使用您购买的或试用的许可证密钥的静态方法。 以下代码片段演示了如何设置许可证密钥:

: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方法来检查用于存储QR码的指定目录是否存在。 如果不存在,则创建该目录。 此方法接受一个字符串参数,该参数是要检查或创建的目录的路径。 以下是它的实现方式:

: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_Generator 类构造函数中定义了 QR 代码目录的路径为 qrCodesDirectory,该路径将应用程序的启动路径与“QR Codes”文件夹名称结合在一起:

: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 格式,根据选择更新 QR 码的前景色或背景色。 它还更新了用户界面以反映新的颜色选择:

: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)当点击时,会打开一个文件对话框,允许用户选择一个图像文件作为logo使用。 此功能对于希望对其二维码进行品牌标识的企业或个人至关重要。 以下是徽标选择和集成过程的处理方式:

: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 二维码生成

生成过程开始于用户点击“生成”按钮,该按钮与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对象定义了错误纠正级别,提高了QR码对损坏或遮挡的抵抗力。 CreateStyleOptions 方法生成一个 QrStyleOptions 对象,其中包括用户的自定义设置,如颜色、尺寸和 logo。 以下是详细的方法:

: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 码生成逻辑使用,以应用用户的偏好设置。 选项包括:

  • 背景颜色和颜色:这些属性设置QR码的背景和前景颜色,允许进行个性化设计,以匹配品牌或审美偏好。
  • 尺寸:此属性决定了二维码的大小,使二维码能够灵活适应不同环境或媒介。
  • 边距:此属性设置 QR 码周围的边距大小,确保其与周围元素隔离,这对可扩展性至关重要。
  • 标志:如果用户选择包含标志,则在此处配置具有特定尺寸和圆角的标志,以获得精致的外观。

4.7 保存二维码

保存功能是通过“保存”按钮触发的,该按钮与 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#

此方法检查是否有生成的二维码可用。 如果是这样,它会提供用户以 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#

此方法重置生成二维码的每个组件。 例如,它清除二维码文本,将尺寸和边距设置为默认值,并移除任何选定的颜色或标志。

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#

步骤五:运行应用程序

当应用程序执行时,主窗口将显示如所提供图片中展示的那样。 布局被整齐地组织成输入、样式、输出和操作几个部分。

应用输出

流程的第一步是在“Input QR Text”字段中输入数据。 此数据将构成二维码的内容,比如一个网址或文本信息。 接下来,要个性化二维码,我们点击“选择标志”按钮来选择一个标志。 选择后,标志将明显放置在按钮相邻的预览框中,确认已将其加入到二维码设计中。

标志

在选择标志后,我们选择二维码的前景色和背景色。 点击相应的按钮后,所选颜色将显示在每个按钮旁边的颜色显示框中,使我们可以立即 visually 确认我们的选择。

颜色选择器

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

尺寸

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

读取 QR 码输出

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

保存对话框

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

成功信息

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

重置表格

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

QR 码输出

结论

总之,本指南已引导您完成了在C#应用程序中使用IronQR库生成QR码的过程。 通过详细介绍在Visual Studio中设置项目、集成IronQR库、设计用户友好界面以及编写后端逻辑的步骤,我们展示了将QR码功能添加到应用程序中的便捷性。

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