使用 IRONQR

如何在C#中創建QR碼生成器應用程式

發佈 2024年5月20日
分享:

歡迎閱讀我們的建立指南 QR碼 使用 C#! QR碼和.NET barcode DLL已成為快速且高效地分享信息的流行方式。無論您是在開發應用程式、管理網站,亦或只是尋找一種整潔的方式來分享鏈接,這些代碼都非常實用。在本指南中,我們將演示如何高效生成QR碼。 IronQR,確保您可以生成適合您需求的 QR 碼。該庫使任何使用 C# 的人都能輕鬆創建 QR 碼,而無需進入複雜的邏輯。我們將引導您完成所有步驟,確保您擁有開始所需的一切。無論您是想為應用程式添加 QR 碼生成功能,還是只是對其工作原理感到好奇,您都來對了地方。讓我們開始吧。

如何在 C# 中创建 QR 码生成器

  1. 在 Visual Studio 中创建一个 Windows Forms 应用程序

  2. 使用 NuGet 安装 QR 库

  3. 设计表单前端元素

  4. 编写 QR 生成的逻辑

  5. 运行应用程序并开始创建 QR 码

IronQR: C# QR 库

IronQR 是一個 C# QR Code 庫,用於將 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;
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
}
using IronQr;
using IronSoftware.Drawing;
using Color = IronSoftware.Drawing.Color;
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
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

我們使用以下的 QR 進行掃描:

如何在 C# 中創建 QR 碼生成應用程式:圖 1 - QR 碼 PNG 圖片檔案

我們得到了這個輸出:

如何在C#中創建QR碼生成器應用程序:圖2 - 讀取QR碼輸出

這個過程首先需要包含必要的命名空間 IronQrIronSoftware.Drawing,特別是從 IronSoftware.Drawing 命名空間中提及的 Color 來處理圖像操作。

在進入QR碼讀取過程之前,必須用您的許可金鑰通過將其分配給 IronQr.License.LicenseKey 來激活軟體。代碼然後使用 AnyBitmap.FromFile 從文件中加載 QR 碼圖像。("QRCode.png")將圖像載入後,下一步涉及準備圖像以進行 QR 碼檢測。這一準備工作是通過創建一個QrImageInput對象來完成的,該對象作為圖像的容器。

此功能的核心在於QrReader類,它被實例化並用來執行 QR 碼讀取操作。閱讀器會分析準備好的圖像qrInput,搜索其中包含的任何 QR 碼。此操作的結果是一些QrResult對象的集合,每個對象代表圖像中檢測到的一個 QR 碼。

為了訪問和利用 QR 碼中編碼的數據,代碼會使用 foreach 循環遍歷結果集合。每個QrResult對象都包含 QR 碼的值等屬性,可以訪問和顯示。

自訂 QR 讀取模式選項

IronQR 提供多種從圖像讀取 QR 碼的方式,適用於各種需求。第一種選項是 混合掃描模式,該模式在速度和精確度之間取得平衡,適用於 QR 碼不清晰或部分隱藏的情況。

另一個選項是 機器學習 (機器學習) 掃描模式,使用智慧技術來讀取損壞或不易正常讀取的 QR 碼。此模式適用於 QR 碼難以偵測的困難情況。

最後,還有 基本掃描模式,這是最快且最簡便的方式來掃描清晰和簡單的 QR 碼。當您需要快速結果且 QR 碼易於讀取時,這是最好的選擇。

using IronQr;
using IronQr.Enum;
using IronSoftware.Drawing;
using Color = IronSoftware.Drawing.Color;
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);
using IronQr;
using IronQr.Enum;
using IronSoftware.Drawing;
using Color = IronSoftware.Drawing.Color;
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 Color = IronSoftware.Drawing.Color
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 碼讀取功能,還提供更深入的互動和資料擷取。

using IronQr;
using IronQr.Enum;
using IronSoftware.Drawing;
using Color = IronSoftware.Drawing.Color;
IronQr.License.LicenseKey = "License-Key";
var imageToScan = AnyBitmap.FromFile("QRCode.png");
QrImageInput qrInput = new QrImageInput(imageToScan);
QrReader qrScanner = new QrReader();
IEnumerable<QrResult> scanResults = qrScanner.Read(qrInput);
foreach (QrResult qrResult in scanResults)
{
    Console.WriteLine(qrResult.Value);
    Console.WriteLine(qrResult.Url);
    foreach (IronSoftware.Drawing.PointF coordinate in qrResult.Points)
    {
        Console.WriteLine($"{coordinate.X}, {coordinate.Y}");
    }
}
using IronQr;
using IronQr.Enum;
using IronSoftware.Drawing;
using Color = IronSoftware.Drawing.Color;
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 IronQr.Enum
Imports IronSoftware.Drawing
Imports Color = IronSoftware.Drawing.Color
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 掃描 QR 碼後,這是輸出的結果:

如何在C#中建立QR碼生成器應用程式:圖3 - 掃描QR碼輸出

我們使用以下 QR Code:

如何在C#中創建 QR 碼生成應用程序:圖4 - QR 碼輸入

每個 QrResult 物件都提供解碼後的數據存取 ()任何嵌入的網址 (網址),與空間座標 (積分) 圖片中 QR code 的內容。

對於每個檢測到的 QR code,IronQR 提供詳細資訊,包括精確內容和 QR code 中包含的任何網址。此外,該庫還提供 QR code 在圖片中的角點的精確坐標。 (通過 Points 屬性)要在 C# 應用程式中使用 IronQR 庫來創建 QR 碼生成器,請仔細按照以下步驟操作。此指南將帶您完成設置 Windows 表單應用程式、安裝 IronQR 庫、編寫生成 QR 碼的代碼,以及理解輸出。

步驟1:在Visual Studio中創建一個Windows應用程式

  • 首先在您的電腦上啟動Visual Studio。
  • 點擊「建立新專案」按鈕。
  • 選擇 Windows Forms App 作為專案類型。確保選擇C#作為語言。

    如何在 C# 中创建 QR 代码生成器应用程序:图 5 - Windows 窗体应用程序

  • 輸入您的專案名稱並選擇要儲存的位置。然後在下一個畫面中,選擇 .NET framework。接著點擊 Create

    如何在 C# 中建立 QR Code 生成應用程式:圖6 - 專案配置

它會在 Visual Studio 中創建並打開一個 Windows 表單應用程式。

第2步:安裝 IronQR 函式庫

現在是時候在專案中安裝 IronQR 函式庫了。您可以通過不同的方法來安裝 IronQR 函式庫。選擇一個適合您偏好的方法:

使用 NuGet 套件管理器安裝

  • 在方案總管中右鍵點擊你的項目,然後選擇 管理 NuGet 套件
  • 在搜索框中輸入 IronQR 並按 Enter。

    如何在 C# 中創建 QR 代碼生成器應用程序:圖 7 - 管理 NuGet 套件

  • 在列表中找到 IronQR,然後點擊旁邊的 Install

    如何在C#中創建一個QR碼生成器應用程序:圖8 - 安裝IronQR

使用 NuGet 套件管理器主控台安裝

  • 前往 工具 > NuGet 套件管理器 > 套件管理器主控台

如何在 C# 中創建 QR 碼生成器應用程序:圖 9 - NuGet 套件管理器

  • 輸入 Install-Package IronQR 並按下 Enter 鍵。

如何在C#中创建QR码生成器应用程式:图10 - 安装IronQR

第三步:設計前端

如何在 C# 中創建 QR Code 生成器應用程序:圖 11 - QR Code 生成器

3.1 標題標頭

如何在 C# 中創建 QR Code 生成器應用程式:圖 12 - 生成 QR Code

啟動 QR 碼生成器應用程式後,用戶立即會看到一個醒目的標題 "QR Generator IronQR",用粗體和權威的字體顯示。選用的字體是 Agency FB,因其簡潔現代的線條而選擇,傳達出效率和精確的感覺。標題的字體大小為 48 點,既突出又自信,吸引了使用者的注意力,並牢固地確立了應用程式的身份。

3.2 輸入部分

QR Code 的文字輸入

如何在 C# 中創建 QR 碼生成器應用程式: 圖 13 - QR 碼文字輸入

在輸入區域的核心是一個簡單但基本的組件:文字輸入框。在這裡,用戶可以輸入他們希望編碼到QR碼中的數據。該框非常寬敞,可以容納大量文本,並顯著地位於頂部附近。

標誌選擇

在 C# 中如何建立 QR 程式生成器應用程式:圖14 - 選擇標誌

在文字輸入框下方,“選擇標誌”區域允許額外的自定義層次。用戶可以上傳一個嵌入QR碼的標誌,從而提升品牌識別或個性化QR碼。旁邊的圖片框提供了所選標誌的預覽,能夠立即看到視覺反饋。

顏色設置

如何用C#創建QR碼生成應用程序:圖15 - 背景顏色

往右移動,介面顯示顏色選擇的選項。有兩個按鈕,一個用於QR碼的顏色,另一個用於背景顏色,讓使用者能夠自定義QR碼的調色盤。這些按鈕旁的富文本框顯示當前選擇的顏色。

輸入部分的精心佈局,帶有文字、標誌和顏色選項,反映了對使用者在創建QR碼時優先事項的清晰理解。它結合了功能性與靈活性,讓使用者能夠快速高效地輸入必要的信息,同時也提供了創意的空間。

3.3 樣式參數

如何在 C# 中創建 QR 碼生成器應用程式:圖 16 - 樣式

尺寸設置

在顏色自訂工具旁,使用者會找到「尺寸」的輸入框。這個數值設置至關重要,因為它決定了 QR 碼的整體大小,確保它能完美適應預期的顯示環境,無論是名片、傳單還是數位屏幕。

邊距設定

在尺寸輸入旁邊,「邊距」欄位允許使用者指定圍繞 QR 碼的白色空間。邊距不僅僅是一種美觀的選擇;它們是一個功能元素,會影響掃描器對 QR 碼的可讀性。應用程序提供了一個數字上下控制,方便使用者輕鬆調整此參數。

3.4 输出预览

如何在C#中創建QR碼生成應用程序:圖17 - QR輸出

一旦用戶啟動QR碼生成,表單左側標記為"Output"的大圖片框就成為焦點。它用作動態顯示,提供生成的QR碼的實時預覽。這個即時的視覺反饋對於用戶來說至關重要,以驗證他們的設計選擇,並確保在保存前QR碼符合他們的期望。

3.5 動作按鈕

生成 QR 码

如何在C#中建立一個QR Code生成器應用程式:圖18 - C#中的QR Code

「生成QR碼」按鈕是應用程式介面中一個重要的控制元素。這個按鈕策略性地放置在表單內,是 QR碼創建過程的催化劑。點擊此按鈕,應用程序會取得用戶定義的所有輸入數據和樣式參數,並開始生成自訂的 QR碼。

儲存 QR Code

如何在C#中创建二维码生成器應用程式:圖19 - 儲存

一旦生成 QR 碼並顯示在輸出預覽區域,"Save QR" 按鈕即可使用。當點擊該按鈕時,它會打開保存對話框,允許用戶選擇所需的文件格式和保存位置。

重設表單

如何用C#創建一個QR碼生成應用程式:圖20 - 重置

只需單擊一下此按鈕,即可清除所有先前的輸入和選擇,將所有設置恢復為默認值。這是表單的一個重要方面,提供了一種快速重新初始化應用程式的方法,而無需手動調整每個選項。

步驟四:編寫後端邏輯

4.1 安裝和初始化

首先,應用程序開始包含必要的命名空間:IronQrIronSoftware.Drawing。這些命名空間是必不可少的,因為它們提供了生成和操作 QR 碼及顏色所需的功能。在 QR 碼生成中使用一個自定義的 Color 類來便於顏色管理,覆蓋默認的 System.Drawing.Color 以確保與 IronQR 的要求兼容。

using IronQr;
using IronSoftware.Drawing;
using Color = IronSoftware.Drawing.Color;
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 元素的一個標準步驟。

public QR_Generator()
{
    InitializeComponent();
    SetLicenseKey();
    EnsureDirectoryExists(qrCodesDirectory);
}
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 Codes"目錄,若不存在則創建該目錄。

4.2 許可證密鑰配置

為了確保 IronQR 能無限制地運行,必須應用有效的許可證密鑰。這可以通過 SetLicenseKey 方法來完成,這是一個用於將您的購買或試用許可證密鑰配置到庫中的靜態方法。下面的代碼片段演示了如何設置許可證密鑰:

private static void SetLicenseKey()
{
    IronQr.License.LicenseKey = "YOUR_LICENSE_KEY";
}
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 碼的目錄是否存在。如果不存在,則會創建該目錄。此方法接受一個 string 參數,即要檢查或創建的目錄路徑。以下是實現方法:

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);
    }
}
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 Codes" 文件夾名稱結合在一起:

string qrCodesDirectory = System.IO.Path.Combine(Application.StartupPath, "QR Codes");
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 用於 QR 碼顏色,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}";
}
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 代碼的前景色或背景色。它還會更新 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;
    }
}
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 ) 當點擊時,會打開一個文件對話框,允許用戶選擇一個圖像文件作為標誌使用。此功能對於希望在其QR碼上進行品牌化的企業或個人來說至關重要。以下是標誌選擇和集成過程的處理方式:

private void btn_logo_Click(object sender, EventArgs e)
{
    if (select_logo.ShowDialog() == DialogResult.OK)
    {
        try
        {
            logoBmp = new AnyBitmap(select_logo.FileName);
            selected_logo.Image = Image.FromFile(select_logo.FileName);
        }
        catch (Exception ex)
        {
            ShowError("An error occurred while loading the logo", ex.Message);
        }
    }
}
private void btn_logo_Click(object sender, EventArgs e)
{
    if (select_logo.ShowDialog() == DialogResult.OK)
    {
        try
        {
            logoBmp = new AnyBitmap(select_logo.FileName);
            selected_logo.Image = Image.FromFile(select_logo.FileName);
        }
        catch (Exception ex)
        {
            ShowError("An error occurred while loading the logo", ex.Message);
        }
    }
}
Private Sub btn_logo_Click(ByVal sender 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 Code 生成

生成過程從用戶點擊“生成”按鈕開始,該按鈕連結到 btn_generate_Click 方法。此方法作為觸發器,調用實際包含生成邏輯的 GenerateQRCode 函數。

private void btn_generate_Click(object sender, EventArgs e)
{
    GenerateQRCode();
}
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 碼的創建,應用所選顏色、尺寸、邊距以及可選的標誌。

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);
    }
}
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 物件,其中包含使用者的自訂設定,例如顏色、尺寸和標誌。以下是該方法的詳細說明:

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
    };
}
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 碼生成邏輯使用該物件來套用用戶的偏好。選項包括:

  • BackgroundColorColor:這些屬性設置 QR 碼的背景色和前景色,允許個性化外觀以符合品牌或美學喜好。
  • Dimensions:此屬性決定 QR 碼的大小,提供在不同上下文或介質中靈活適應的能力。
  • Margins:此屬性設定 QR 碼周圍的邊距大小,確保它與周圍元素隔離,這對於擴展性可能至關重要。
  • Logo:如果用戶選擇包括標誌,這裡可以配置標誌的具體尺寸和圓角半徑,以達到精緻外觀。

4.7 儲存 QR 碼

儲存功能是通過連結到 btn_save_Click 方法的“儲存”按鈕觸發的。此方法會調用 SaveQRCode,該方法實現了儲存邏輯。過程包括顯示一個儲存文件對話框,允許使用者選擇儲存 QR 碼的文件格式和位置。

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);
        }
    }
}
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 函數確保圖像根據使用者選擇的檔案擴展名以正確的格式儲存。

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;
}
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#

這種彈性讓使用者可以選擇最適合他們需求的格式,無論是優先考慮品質 (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 = System.Drawing.Color.White;
    txt_selected_bgcolor.BackColor = System.Drawing.Color.Black;
    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 = 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 碼生成中涉及的每個元件。例如,它會清除 QR 碼文字,將尺寸和邊界設置為預設值,並移除任何選定的顏色或標誌。

4.9 錯誤處理

應用程式使用 ShowError 方法以用戶友好的方式顯示錯誤消息。此方法接受兩個參數:標題和消息,這些參數為用戶提供有關錯誤的上下文。以下是其實現方式:

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");
}
Private Shared Sub ShowError(ByVal title As String, ByVal message As String)
	MessageBox.Show($"{title}: {message}", "Error")
End Sub
VB   C#

此方法在應用程式的不同部分被使用,以確保當發生錯誤時,用戶立即被通知一個清晰明了的信息。例如,如果在加載標誌或生成 QR 代碼的過程中發生錯誤,應用程式會調用 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");
        }
    }
}
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#

第五步:運行應用程序

當應用程序執行時,主窗口會如所提供的圖片所示顯示。佈局整齊地組織成輸入、樣式、輸出和操作的部分。

如何在C#中創建QR碼生成器應用程式: 圖21 - 應用程式輸出

第一步是將數據輸入到“輸入QR文本”字段。這些數據將構成QR碼的內容,例如URL或文本信息。接下來,為了個性化QR碼,我們通過點擊“選擇徽標”按鈕選擇一個徽標。選擇後,徽標會顯示在按鈕旁邊的預覽框中,確定其已納入QR碼設計。

如何在C#中創建一個QR碼生成器應用程式:圖22 - Logo

在選擇標誌後,我們選取 QR 碼的前景色和背景色。點擊相應按鈕後,選擇的顏色會顯示在每個按鈕旁邊的顏色顯示框內,立即視覺確認我們的選擇。

如何在C#中創建 QR Code 生成器應用程式:圖 23 - 顏色選擇

針對這個特定的 QR 條碼,我們將其尺寸設置為 500,確保條碼的大小適合我們的需求,並將邊距調整為 20,以在 QR 條碼周圍提供緩衝區,防止掃描問題。

如何在C#中創建一個QR碼生成應用程式:圖24 - 尺寸

在設定好所有輸入和樣式選項後,我們點擊"生成 QR"按鈕來生成 QR 碼。應用程式處理我們的輸入,並在輸出圖片框中顯示新創建的 QR 碼。

如何在 C# 中創建 QR 碼生成器應用程式:圖 25 - 讀取 QR 碼輸出

要保存生成的 QR 碼,我們只需點擊「Save QR」按鈕。此操作會打開一個保存對話框,允許我們選擇 QR 碼圖片的目的地和文件格式。

如何在C#中創建二維碼生成應用程式:圖26 - 儲存對話框

儲存後,成功消息確認 QR 碼已成功存儲。

如何在 C# 中創建 QR 碼生成應用程序:圖 27 - 成功消息

如果我們需要重新開始或創建新的QR碼,點擊「重置表單」按鈕將表單恢復到原始狀態,清除所有欄位和選擇,準備生成下一個QR碼。

如何在 C# 中創建 QR Code 生成器應用程式:圖 28 - 重置表單

以下是由 IronQR 生成的已保存 QR 代碼:

如何在C#中創建QR碼生成應用程序:圖29 - QR碼輸出

結論

總而言之,本指南已帶您完成在 C# 應用程序中使用 IronQR 庫生成 QR 碼的過程。通過分解從在 Visual Studio 中設定專案、整合 IronQR 庫、設計用戶友好的界面以及撰寫後端邏輯的步驟,我們展示了如何輕鬆地將 QR 碼功能添加到您的應用程序中。

對於那些有興趣進一步探索 IronQR 功能的人而言,值得注意的是,IronQR 提供了 免費試用 讓你開始。如果您決定將IronQR整合到您的項目中,許可證起始價格為$749,提供了一個經濟有效的解決方案,用於生成專業級的QR碼。

< 上一頁
如何在 C# 中读取 QR 代码
下一個 >
如何在 .NET 6 中使用 QRCoder 和 IronQR 生成 QR 碼

準備開始了嗎? 版本: 2024.10 剛剛發布

免費 NuGet 下載 總下載次數: 17,050 查看許可證 >