如何在 C# 中创建 QR 代码生成器应用
欢迎使用我们的指南,了解如何使用C# 创建QR码! QR码和.NET条形码DLL已成为快速高效分享信息的流行方式。 无论您是在开发应用程序,管理网站,还是只是寻找一种整洁的方式分享链接,这些代码都能非常有用。 在本指南中,我们将演示如何使用IronQR高效生成QR码,确保您能生成满足您需求的QR码。 这个库使任何使用C#的人都可以轻松创建QR码,而无需深入复杂的逻辑。 我们将引导您完成每一步,确保您拥有开始所需的一切。 无论您是想在应用程序中添加QR码生成器功能还是只想了解它是如何完成的,您都来对地方了。 让我们开始吧。
如何在C#中创建QR码生成器
- 在Visual Studio中创建Windows Forms应用程序
- 使用NuGet安装QR库
- 设计表单前端元素
- 编写QR生成逻辑
- 运行应用程序并开始创建QR码
IronQR:C# QR库
IronQR是一个C# QR码库,用于将QR码功能集成到.NET应用程序中。 IronQR支持多种.NET版本和项目类型,包括C#、VB.NET、F#、.NET Core、.NET Standard、.NET Framework等,确保与各种开发环境兼容,如Windows、Linux、macOS、iOS和Android。
IronQR以其高级功能而著称,包括读取QR码和生成QR码、支持多种图像格式以及诸如重新调整大小、样式和在QR码上添加徽标等定制选项。
IronQR的一些关键功能
IronQR不仅限于基本的QR码生成,还提供多种功能,旨在适应各种与QR码相关的任务。 让我们来看看这些功能并检查它们的示例代码,您可以将它们集成到任何类型的.NET应用程序模板中,如控制台应用程序。
读取QR码
IronQR在解码QR码方面表现出色,为用户提供了一种访问嵌入在QR码中的信息的简单方法。 您可以快速准确地从QR码中提取数据,从简单的URL到复杂的嵌入信息皆可。
using IronQr;
using IronSoftware.Drawing;
using Color = IronSoftware.Drawing.Color;
// Set the license key for IronQR
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);
// Print the value of each QR code found in the image
foreach (var result in qrResults)
{
Console.WriteLine(result.Value);
}using IronQr;
using IronSoftware.Drawing;
using Color = IronSoftware.Drawing.Color;
// Set the license key for IronQR
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);
// Print the value of each QR code found in the image
foreach (var result in qrResults)
{
Console.WriteLine(result.Value);
}我们使用以下QR进行扫描:

并获得了以下输出:

该过程首先要结合必要的命名空间IronQr和Iron Software.Drawing,特别提到Iron Software.Drawing命名空间中的Color来处理图像操作。
在深入QR码读取过程之前,必须通过将许可证密钥分配给IronQr.License.LicenseKey来激活软件。 然后代码继续使用AnyBitmap.FromFile("QRCode.png")从文件加载QR码图像。
加载图像后,下一步就是准备它以进行QR码检测。 此准备通过创建一个QrImageInput对象完成,该对象充当图像的容器。
此功能的核心在于QrReader类,它被实例化并用于执行QR码读取操作。 读取器分析已准备的图像qrInput,寻找其中的任何QR码。 该操作的结果是一个QrResult对象的集合,每个对象代表图像中检测到的一个QR码。
要访问和利用QR码中编码的数据,代码使用foreach循环遍历结果集。每个QrResult对象包含诸如QR码的值等属性,可以访问并显示。
自定义QR读取模式选项
IronQR为您提供不同的方法从图像中读取QR码,使其适应各种需求。 其中一个选项是混合扫描模式,它平衡了速度和准确性,适用于QR码不清晰或部分隐藏的情况。
另一个选项是机器学习(ML)扫描模式,它使用智能技术读取受损或以通常方式不易读取的QR码。 此模式非常适用于在QR码难以检测的艰难情况下。
最后,还有基本扫描模式,这是扫描清晰且简单QR码的最快和最简单的方法。 它最适合当您需要快速结果且QR码易读。
using IronQr;
using IronQr.Enum;
using IronSoftware.Drawing;
using Color = IronSoftware.Drawing.Color;
// Set the license key for IronQR
IronQr.License.LicenseKey = "License-Key";
// Load the image file that contains the QR Code
var inputImage = AnyBitmap.FromFile("QRCode.png");
// Using mixed scan mode
QrImageInput mixedScanInput = new QrImageInput(inputImage, QrScanMode.OnlyDetectionModel);
IEnumerable<QrResult> mixedScanResults = new QrReader().Read(mixedScanInput);
// Using machine learning scan mode
QrImageInput mlScanInput = new QrImageInput(inputImage, QrScanMode.OnlyDetectionModel);
IEnumerable<QrResult> mlScanResults = new QrReader().Read(mlScanInput);
// Using basic scan mode
QrImageInput basicScanInput = new QrImageInput(inputImage, QrScanMode.OnlyBasicScan);
IEnumerable<QrResult> basicScanResults = new QrReader().Read(basicScanInput);using IronQr;
using IronQr.Enum;
using IronSoftware.Drawing;
using Color = IronSoftware.Drawing.Color;
// Set the license key for IronQR
IronQr.License.LicenseKey = "License-Key";
// Load the image file that contains the QR Code
var inputImage = AnyBitmap.FromFile("QRCode.png");
// Using mixed scan mode
QrImageInput mixedScanInput = new QrImageInput(inputImage, QrScanMode.OnlyDetectionModel);
IEnumerable<QrResult> mixedScanResults = new QrReader().Read(mixedScanInput);
// Using machine learning scan mode
QrImageInput mlScanInput = new QrImageInput(inputImage, QrScanMode.OnlyDetectionModel);
IEnumerable<QrResult> mlScanResults = new QrReader().Read(mlScanInput);
// Using basic scan mode
QrImageInput basicScanInput = new QrImageInput(inputImage, QrScanMode.OnlyBasicScan);
IEnumerable<QrResult> basicScanResults = new QrReader().Read(basicScanInput);读取高级QR码
IronQR的高级QR码读取能力旨在提供对QR码扫描和解码的全面而细致的处理。 这一功能集不仅限于基本的QR码读取功能,还提供更深层次的互动和数据提取。
using IronQr;
using IronQr.Enum;
using IronSoftware.Drawing;
using Color = IronSoftware.Drawing.Color;
// Set the license key for IronQR
IronQr.License.LicenseKey = "License-Key";
// Load the image to scan
var imageToScan = AnyBitmap.FromFile("QRCode.png");
// Prepare the image for QR code detection
QrImageInput qrInput = new QrImageInput(imageToScan);
// Initialize the QR Code reader
QrReader qrScanner = new QrReader();
// Execute QR Code reading on the provided image
IEnumerable<QrResult> scanResults = qrScanner.Read(qrInput);
// Print the value, URL, and coordinates of each QR code found in the image
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 IronQr.Enum;
using IronSoftware.Drawing;
using Color = IronSoftware.Drawing.Color;
// Set the license key for IronQR
IronQr.License.LicenseKey = "License-Key";
// Load the image to scan
var imageToScan = AnyBitmap.FromFile("QRCode.png");
// Prepare the image for QR code detection
QrImageInput qrInput = new QrImageInput(imageToScan);
// Initialize the QR Code reader
QrReader qrScanner = new QrReader();
// Execute QR Code reading on the provided image
IEnumerable<QrResult> scanResults = qrScanner.Read(qrInput);
// Print the value, URL, and coordinates of each QR code found in the image
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}");
}
}这是我们使用IronQR扫描QR码时获得的输出:

我们使用以下QR码:

每个QrResult对象提供对解码数据(Value)、任何嵌入的URL(Url)以及QR码在图像中的空间坐标(Points)的访问。
对于每个检测到的QR码,IronQR提供详细信息,包括QR码内包含的确切内容和任何URL。 此外,库还提供QR码在图像中角落的精确坐标(通过Points属性)。
要在C#应用程序中使用IronQR库创建一个QR码生成器,请仔细按照这些步骤进行。 本指南将带您从设置Windows窗体应用程序、安装IronQR库、编写生成QR码的代码到理解输出。
步骤1:在Visual Studio中创建Windows应用程序
- 首先,在您的计算机上启动Visual Studio。
- 点击"创建新项目"按钮。
- 选择Windows Forms App作为项目类型。 确保选择C#语言。

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

这将在Visual Studio中创建并打开一个Windows窗体应用程序。
步骤2:安装IronQR库
现在是时候在项目中安装IronQR库了。 您可以通过不同的方法安装IronQR库。 选择一个符合您偏好的方法:
使用NuGet包管理器安装
- 在Solution Explorer中右键单击您的项目并选择管理NuGet软件包。
- 在搜索框中键入IronQR并按Enter。

- 在列表中找到IronQR并点击旁边的安装。

使用NuGet包管理器控制台安装
- 前往工具 > NuGet包管理器 > 包管理器控制台。

- 键入Install-Package IronQR并按下Enter。

步骤3:设计前端

3.1 标题头

启动QR码生成器应用程序后,用户立即会看到一个引人注目的标题,名为"QR Generator IronQR",以一种粗体和权威的字体书写。 选择Agency FB字体是因为其线条干净现代,传达出高效和精准的感受。 以48点大小的字体,标题既突出又自信,捕捉用户的注意力,并牢固确立应用程序的身份。
3.2 输入部分
QR码的文本输入

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

在文本输入之下,"选择徽标"区域允许用户进行额外的个性化定制。 用户可以上传一个将被嵌入在QR码中的徽标,增强品牌识别或使代码个性化。 相邻的图片框提供了选定徽标的预览,提供了即时的视觉反馈。
颜色配置

右侧的界面提供颜色选择的选项。 两个按钮,一个用于QR码的颜色,另一个用于背景颜色,允许用户自定义他们的QR码调色板。 这些按钮旁边的富文本框显示了当前选定的颜色。
输入部分合理布局,结合文本、徽标和颜色选项,用户可快速输入信息并留有创作余地。 它将功能与灵活性相结合,允许用户快速高效地输入所需的信息,同时也提供了创造性的空间。
3.3 样式参数
维度设置
在颜色定制工具旁,用户会找到"维度"输入。这个数值设置是关键,因为它决定了QR码的整体尺寸,确保其完美地适应预定的显示上下文,无论是名片、传单还是数字屏幕。
边距设置
边距设置
边距不仅仅是美学选择;它们是一个功能元素,可以影响扫描仪对QR码的可读性。 应用程序提供了一个数字上下控制,方便用户调整这个参数。 ### 3.4 输出预览


它充当动态显示,提供生成的QR码的实时预览。 这种即时的视觉反馈对用户验证他们的设计选择并确保QR码在保存前满足他们的期望至关重要。 ### 3.5 动作按钮
生成QR


此按钮被战略性地放置在表单内,是启动QR码创建过程的催化剂。 点击此按钮后,应用程序就会将用户定义的所有输入数据和样式参数并开始自定义QR码的生成。 #### 保存QR码


点击后,它会打开一个保存对话框,允许用户选择所需的文件格式和保存位置。 #### 重置表单


这是表单的重要方面,提供一种快速重新初始化应用程序而无需手动调整每个选项的方法。 这是表单的一个重要方面,提供了一种快速的方式来重新初始化应用程序,而无需手动调整每个选项。
第4步:编写后端逻辑
4.1 设置和初始化
首先,应用程序开始时要包含必要的命名空间:IronQr和Iron Software.Drawing。 定义自定义Color类以简化QR码生成中的颜色管理,覆盖默认的System.Drawing.Color以确保与IronQR的要求兼容。 QR_Generator类的构造函数在准备应用程序使用中起着至关重要的角色。
using IronQr;
using IronSoftware.Drawing;
using Color = IronSoftware.Drawing.Color;using IronQr;
using IronSoftware.Drawing;
using Color = IronSoftware.Drawing.Color;QR_Generator 类的构造函数在准备应用程序以供使用方面起着至关重要的作用。 * SetLicenseKey:此方法被调用以应用IronQR库的有效许可证密钥。
public QR_Generator()
{
InitializeComponent();
SetLicenseKey();
EnsureDirectoryExists(qrCodesDirectory);
}public QR_Generator()
{
InitializeComponent();
SetLicenseKey();
EnsureDirectoryExists(qrCodesDirectory);
}SetLicenseKey:调用此方法以应用有效的 IronQR 库许可证密钥。 *EnsureDirectoryExists:鉴于需要保存生成的QR码,此方法确保存在一个专用目录。EnsureDirectoryExists:鉴于需要保存生成的 QR 代码,此方法确保有一个专用目录可用。 它检查应用程序启动路径下是否存在"QR Codes"目录,如果不存在,则创建它。
为了确保IronQR无限制运行,必须应用有效的许可证密钥。
通过SetLicenseKey方法来实现,这是一个静态方法,用于用您购买或试用的许可证密钥配置库。 这是通过 SetLicenseKey 方法实现的, 该方法是一个静态方法,旨在使用您购买或试用的许可证密钥来配置库。 下面的代码片段演示了如何设置许可证密钥:
private static void SetLicenseKey()
{
IronQr.License.LicenseKey = "YOUR_LICENSE_KEY";
}private static void SetLicenseKey()
{
IronQr.License.LicenseKey = "YOUR_LICENSE_KEY";
}该方法在QR_Generator类的构造函数中调用,确保许可证在应用程序启动和任何QR码生成开始之前就已应用。 ### 4.3 目录管理
该应用程序使用EnsureDirectoryExists方法来检查存储QR码的指定目录是否存在。
应用程序使用 EnsureDirectoryExists 方法检查用于存储 QR 代码的指定目录是否存在。 该方法接受一个string参数,即要检查或创建的目录路径。 此方法接受一个 string 参数,即要检查或创建的目录路径。 此方法利用System.IO命名空间与文件系统交互。
private static void EnsureDirectoryExists(string path)
{
if (!System.IO.Directory.Exists(path))
{
System.IO.Directory.CreateDirectory(path);
}
}private static void EnsureDirectoryExists(string path)
{
if (!System.IO.Directory.Exists(path))
{
System.IO.Directory.CreateDirectory(path);
}
}此方法利用System.IO命名空间与文件系统进行交互。 它首先使用Directory.Exists检查指定路径下的目录是否存在。 QR码目录的路径在QR_Generator类构造函数中定义为qrCodesDirectory,其结合了应用程序的启动路径和"QR Codes"文件夹名称:
4.4 颜色选择
string qrCodesDirectory = System.IO.Path.Combine(Application.StartupPath, "QR Codes");string qrCodesDirectory = System.IO.Path.Combine(Application.StartupPath, "QR Codes");该应用程序在用户界面中提供了两个按钮,每个按钮都绑有一个用于选择颜色的方法:btn_color_Click用于QR码颜色,btn_background_Click用于背景颜色。
该应用程序在用户界面上提供了两个按钮,每个按钮都与选择颜色的方法相关联:btn_color_Click 用于二维码颜色,btn_background_Click 用于背景颜色。 当使用颜色对话框选择颜色时,所选颜色将被转换为十六进制字符串格式。
当使用颜色对话框选择颜色时,所选择的颜色将转换为十六进制字符串格式。 这是必要的,因为IronQR库要求以十六进制格式指定颜色。 转换通过ColorToHex方法完成:
private string ColorToHex(System.Drawing.Color color)
{
return $"#{color.R:X2}{color.G:X2}{color.B:X2}";
}private string ColorToHex(System.Drawing.Color color)
{
return $"#{color.R:X2}{color.G:X2}{color.B:X2}";
}UpdateColor方法获取所选择的颜色,并使用十六进制字符串将其转换为Iron Software.Drawing.Color格式,并根据选择更新二维码的前景或背景颜色。 它还更新UI以反映新的颜色选择:
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 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 添加徽标
应用程序包含一个按钮(btn_logo_Click),点击时打开文件对话框,允许用户选择用于徽标的图像文件。 此功能对希望为其二维码品牌化的企业或个人至关重要。 以下是徽标选择和集成过程的处理方式:
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);
}
}
}成功选择图像后,应用程序尝试加载它并显示预览。 AnyBitmap对象logoBmp随后设置为所选图像,二维码生成逻辑随后将使用此图像。
4.6 QR码生成
生成过程在用户单击"生成"按钮时开始,该按钮链接到btn_generate_Click方法。 此方法充当触发器,调用GenerateQRCode函数,实际生成逻辑在此处。
private void btn_generate_Click(object sender, EventArgs e)
{
GenerateQRCode();
}private void btn_generate_Click(object sender, EventArgs e)
{
GenerateQRCode();
}在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 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);
}
}QrOptions对象定义错误纠正级别,提高二维码抵御损坏或遮挡的能力。 CreateStyleOptions方法生成QrStyleOptions对象,其中包括用户的自定义设置,如颜色、尺寸和徽标。 这里是详细的方法:
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 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
};
}此方法创建一个 QrStyleOptions 对象,随后由二维码生成逻辑使用,以应用用户的偏好。 选项包括:
BackgroundColor和Color:这些属性设置二维码的背景色和前景色,从而实现个性化外观,以匹配品牌或审美偏好。Dimensions:此属性决定二维码的大小,使二维码能够灵活地适应不同的环境或媒介。Margins:此属性设置二维码周围的边距大小,确保其与周围元素隔离,这对于可扩展性至关重要。Logo:如果用户选择添加徽标,则会在此处配置徽标的特定尺寸和圆角半径,以获得更精致的外观。
4.7 保存二维码
保存功能通过"保存"按钮触发,该按钮链接到 btn_save_Click 方法。 此方法调用 SaveQRCode,实现保存逻辑。 该过程包括显示保存文件对话框,允许用户选择保存二维码的文件格式和位置。
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 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);
}
}
}此方法检查是否有生成的二维码可用。 如果有,它将向用户提供将文件保存为 PNG 或 JPEG 格式的选项。 DetermineImageFormat 函数确保图像根据用户选择的文件扩展名以正确的格式保存。
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 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;
}这种灵活性允许用户选择最适合其需求的格式,无论是优先考虑质量(PNG)还是文件大小(JPEG)。
4.8 重置应用程序
重置功能链接到"重置"按钮,该按钮调用 btn_reset_Click 方法。 该方法随后调用 ResetFields,该函数旨在清除所有用户输入并恢复所有设置的默认值,包括文本字段、颜色选择和所选徽标。
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 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;
}此方法重置二维码生成中涉及的每个组件。 例如,它清除二维码文本,将尺寸和边距设置为默认值,并删除任何选择的颜色或logo。
4.9 错误处理
该应用程序使用 ShowError 方法以用户友好的方式显示错误消息。 该方法在应用程序的不同部份中被利用,以确保当发生错误时,能立即通过一个清晰简洁的信息通知用户。 此方法利用System.IO命名空间与文件系统交互。
private static void ShowError(string title, string message)
{
MessageBox.Show($"{title}: {message}", "Error");
}private static void ShowError(string title, string message)
{
MessageBox.Show($"{title}: {message}", "Error");
}此方法在应用程序的不同部分中使用,以确保当发生错误时,用户会被及时以清晰简明的消息通知。 例如,如果在加载logo时或在生成二维码过程中发生错误,应用程序会调用 ShowError 来显示有关问题的详细信息。
4.10 完整代码示例
这是完整代码,帮助您更容易理解代码:
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");
}
}
}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");
}
}
}步骤 5:运行应用程序
布局整齐地分为输入、样式、输出和操作部分。 

该过程的第一步涉及在"输入二维码文本"字段中输入数据。 接下来,为了个性化QR码,通过点击"选择徽标"按钮选择一个徽标。 选择后,徽标被明显地放置在按钮旁边的预览框中,确认其已经合并到QR码设计中。 

点击相应的按钮后,选择的颜色在每个按钮旁边的颜色显示框中反映,立即提供了对我们选择的视觉确认。 



应用程序处理我们的输入并在输出图片框中显示新创建的QR码。 应用程序处理我们的输入并在输出图片框中显示新创建的二维码。

要保存生成的二维码,我们只需点击"保存二维码"按钮。 这项操作打开一个保存对话框,允许我们选择QR代码图像的目标和文件格式。
!如何创建一个C#的QR代码生成器应用程序:图26 - 保存对话框
一旦保存,成功消息确认QR代码已成功存储。

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

这是由IronQR生成的已保存二维码:

结论
总之,本指南引导您完成在C#应用程序中使用IronQR库生成二维码的过程。 通过分解从在Visual Studio中设置项目、集成IronQR库、设计用户友好的界面到编写后端逻辑的步骤,我们展示了为您的应用程序添加二维码功能的便捷性。
对于那些有兴趣进一步探索IronQR功能的人,值得注意的是,IronQR提供了一个免费试用供您入门。 如果您决定将IronQR集成到您的项目中,许可证的起价为$799,为专业级QR代码生成提供了具有成本效益的解决方案。
常见问题解答
如何在C#中创建二维码生成器应用程序?
要在C#中创建二维码生成器应用程序,首先在Visual Studio中设置Windows窗体应用程序。通过NuGet安装IronQR库,设计带有文本、徽标和颜色输入字段的界面,然后使用IronQR的方法实现二维码生成逻辑。
C#中的二维码有哪些定制选项?
IronQR提供了二维码的定制选项,例如更改颜色、尺寸和边距。你也可以通过在QrStyleOptions对象中调整设置来向二维码中添加徽标。
如何在C#项目中安装二维码库?
在Visual Studio中使用NuGet包管理器安装IronQR库到你的C#项目中。搜索IronQR并点击“安装”按钮将其添加到你的项目中。
我可以使用哪些格式在C#中保存生成的二维码?
使用IronQR,可以生成并保存为包括PNG和JPEG在内的各种格式的二维码,以便在质量和文件大小方面灵活选择。
我可以使用C#库读取二维码吗?
是的,IronQR包括读取二维码的功能,使得可以有效地解码和提取QR图像中的数据。
使用C#二维码库有什么好处?
像IronQR这样的C#二维码库简化了生成和读取二维码的过程,它提供多格式支持、定制选项以及与各种.NET版本的兼容性。
如何在C#中处理二维码生成时的错误?
可以通过在C#中使用try-catch块将错误处理集成到二维码生成应用程序中。这样可以确保在生成二维码过程中出现的任何问题得到顺利处理,并提供用户友好的反馈。
在C#应用程序中使用二维码库需要许可证吗?
是的,若要不受限制地使用IronQR,您需要一个有效的许可证密钥。试用版可用于初步测试,购买专业许可证可以获得完整访问权限。
如何在C#中将徽标集成到二维码中?
使用IronQR,可以通过在QrStyleOptions对象中设置徽标图像来将徽标集成到二维码中。这允许您使用品牌元素个性化二维码。
运行C#中的二维码生成应用程序的步骤是什么?
在C#中设置并自定义二维码生成应用程序后,只需在Visual Studio中运行该应用程序,生成二维码,并使用提供的选项保存为您所需的格式。






