如何在 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);
}
Imports IronQr
Imports IronSoftware.Drawing
Imports Color = IronSoftware.Drawing.Color
' Set the license key for IronQR
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)
' Print the value of each QR code found in the image
For Each result In qrResults
Console.WriteLine(result.Value)
Next result
我們使用以下QR碼進行掃描:

我們得到了這個輸出:

此過程首先引入必要的命名空間,IronSoftware.Drawing命名空間,用於處理圖像操作。
在深入QR碼識別過程前,首先需使用您的授權金鑰激活軟體,將其分配給IronQr.License.LicenseKey。 然後,程式碼將QR碼圖像從文件中載入,使用AnyBitmap.FromFile("QRCode.png")。
圖像載入後,下一步是為QR碼檢測做好準備。 這一準備工作是通過建立QrImageInput物件來完成的,該物件用作圖像的容器。
此功能的核心在於QrReader類別,該類別被實例化並用於執行QR碼識別操作。 讀取器分析準備好的圖像,qrInput,搜尋其中包含的任何QR碼。 此操作的結果是一系列QrResult物件,每個物件表示圖像中檢測到的QR碼。
要存取和使用QR碼中編碼的資料,程式碼會使用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);
Imports IronQr
Imports IronQr.Enum
Imports IronSoftware.Drawing
Imports Color = IronSoftware.Drawing.Color
' Set the license key for IronQR
IronQr.License.LicenseKey = "License-Key"
' Load the image file that contains the QR Code
Dim inputImage = AnyBitmap.FromFile("QRCode.png")
' Using mixed scan mode
Dim mixedScanInput As New QrImageInput(inputImage, QrScanMode.OnlyDetectionModel)
Dim mixedScanResults As IEnumerable(Of QrResult) = (New QrReader()).Read(mixedScanInput)
' Using machine learning scan mode
Dim mlScanInput As New QrImageInput(inputImage, QrScanMode.OnlyDetectionModel)
Dim mlScanResults As IEnumerable(Of QrResult) = (New QrReader()).Read(mlScanInput)
' Using basic scan mode
Dim basicScanInput As New QrImageInput(inputImage, QrScanMode.OnlyBasicScan)
Dim basicScanResults As IEnumerable(Of QrResult) = (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}");
}
}
Imports IronQr
Imports IronQr.Enum
Imports IronSoftware.Drawing
Imports Color = IronSoftware.Drawing.Color
' Set the license key for IronQR
IronQr.License.LicenseKey = "License-Key"
' Load the image to scan
Dim imageToScan = AnyBitmap.FromFile("QRCode.png")
' Prepare the image for QR code detection
Dim qrInput As New QrImageInput(imageToScan)
' Initialize the QR Code reader
Dim qrScanner As New QrReader()
' Execute QR Code reading on the provided image
Dim scanResults As IEnumerable(Of QrResult) = qrScanner.Read(qrInput)
' Print the value, URL, and coordinates of each QR code found in the image
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
以下是我們使用IronQR掃描QR碼的輸出:

我們使用以下二維碼:

每個Points)的存取。
對於每個檢測到的QR碼,IronQR提供詳細資訊,包括QR碼內含的確切內容和任何URL。 此外,程式庫提供了圖像中QR碼角落的精確坐標(通過Points屬性)。
要在C#應用程式中使用IronQR的QR碼程式庫建立QR碼生成器,請仔細按照以下步驟進行。 本指南將帶您逐步完成設置Windows表單應用程式、安裝IronQR程式庫、編寫程式碼生成QR碼並理解輸出的過程。
步驟1:在Visual Studio中建立Windows應用程式
- 首先在您的電腦上啟動Visual Studio。
- 點擊"建立新專案"按鈕。
- 選擇Windows Forms App作為專案型別。 確保選擇C#作為語言。

- 輸入專案名稱並選擇保存位置。 然後在下一個畫面選擇.NET framework。 然後點擊建立。

它將在Visual Studio中建立並打開一個Windows表單應用程式。
步驟2:安裝IronQR程式庫
現在是時候在專案中安裝IronQR程式庫了。 您可以通過不同的方法安裝IronQR程式庫。 選擇一個適合您偏好的方法:
使用NuGet套件管理器安裝
- 右鍵單擊您在解決方案資源管理器中的專案並選擇管理NuGet包。
- 在搜索框中輸入IronQR並按Enter。

- 在列表中找到IronQR並點擊旁邊的安装。

使用NuGet套件管理器控制台安裝
- 前往工具 > NuGet套件管理器 > 套件管理器控制台。

- 輸入
Install-Package IronQr並按Enter。

步驟3:設計前端

3.1 標題標頭

啟動QR Code Generator應用程式後,使用者首先會看到一個醒目的標題,名為"QR Generator IronQR",字體設為醒目且具權威的樣式。 選擇了字體Agency FB,因其清晰、現代的線條能夠傳達效率和精準感。 字體大小為48點,既顯著又肯定,吸引使用者注意力並牢固確立應用程式的身份。
3.2 輸入區域
QR碼文字輸入

輸入區域的核心是一個簡單但至關重要的組件:文字輸入框。 在這裡,使用者可以輸入他們希望編碼進QR碼中的資料。 文字框寬敞,能容納大量文字,並顯著地位於頂部附近。
徽標選擇

在文字輸入的下方,"選擇徽標"區域允許進行額外的自訂。 使用者可以上傳一個將嵌入QR碼中的徽標,提高品牌認知或個性化程式碼。 相鄰的圖片框提供了所選徽標的預覽,即時提供視覺反饋。
顏色配置

移到右側,介面提供顏色選擇選項。 兩個按鈕,其中一個用於QR碼的顏色,另一個用於背景顏色,使使用者能夠自訂QR碼的配色方案。 這些按鈕旁邊的富文字框顯示當前選定的顏色。
輸入區域的經心布局,包含文字、徽標和顏色選項,反映出對使用者在建立QR碼時優先事項的明確了解。 它結合了功能性和靈活性,讓使用者快速有效地輸入必需的資訊,還提供創意空間。
3.3 樣式參數

尺寸設置
在顏色自訂工具旁,使用者會找到"尺寸"的輸入項。此數值設置至關重要,因為它決定了QR碼的整體大小,確保其能準確適應業務卡、傳單或數位螢幕等目的展示背景。
邊界設置
在尺寸輸入旁,"邊距"字段允許使用者指定QR碼周圍的空白區域。 邊距不僅僅是一個美學選擇,它是影響掃描器讀取QR碼的功能性元素。 應用程式提供了一個數值上下控制,使用者可以輕鬆調整參數。
3.4 輸出預覽

當使用者啟動QR碼生成時,位於表單左側的大圖片框,標記為"輸出",成為焦點。 其提供動態顯示,提供生成QR碼的即時預覽。 此即時視覺反饋對於使用者驗證其設計選擇,並在保存前確保QR碼符合其預期尤其重要。
3.5 行動按鈕
生成QR

"生成QR"按鈕是應用程式介面中的關鍵控制元素。 策略性地位於表單內,此按鈕是QR碼建立過程的催化劑。 點擊此按鈕後,應用程式採取所有的輸入資料和使用者定義的樣式參數,並開始生成定制QR碼。
保存QR碼

生成並在輸出預覽區域顯示QR碼後,"保存QR"按鈕發揮作用。 點擊後,它會打開一個保存對話框,讓使用者選擇所需的文件格式和保存位置。
重置表單

只需單擊此按鈕,就能清除所有先前的輸入和選擇,將所有設置恢復為預設值。 這是表單的重要方面,提供了一種快速的方法來重新初始化應用程式,而無需手動調整每個選項。
步驟4:編寫後端邏輯
4.1 設置和初始化
首先,應用程式開始包含必要的命名空間:IronSoftware.Drawing。 這些命名空間是必須的,因為它們提供了在應用程式中生成和操作QR碼和顏色所需的功能。 自訂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
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
-
SetLicenseKey:此方法被調用以應用IronQR程式庫的有效授權密鑰。 授權密鑰的使用是商業應用程式的必需品,並解鎖IronQR程式庫的全功能。 EnsureDirectoryExists:需要保存生成的QR碼,這個方法確保有可用的專用目錄。 它檢查應用程式啟動路徑是否存在"QR程式碼"目錄,如果不存在則建立它。
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
用您從Iron Software獲得的實際授權金鑰替換"YOUR_LICENSE_KEY"。 該方法被呼叫於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
該方法利用System.IO命名空間與文件系統互動。 它首先使用Directory.Exists檢查指定路徑上的目錄是否存在。 如果目錄不存在(Directory.CreateDirectory建立目錄。
QR碼目錄的路徑在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")
4.4 顏色選擇
應用程式在使用者介面上提供了兩個按鈕,每個按鈕都與一個選擇顏色的方法綁定: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
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
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
成功選擇圖像後,應用程式嘗試載入並顯示預覽。 然後logoBmp即被設置為選定圖像,QR生成邏輯稍後會使用它。
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();
}
Private Sub btn_generate_Click(ByVal sender As Object, ByVal e As EventArgs)
GenerateQRCode()
End Sub
在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
QrOptions物件定義了錯誤更正級別,增強了QR碼對損壞或遮蔽的抵抗力。 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
此方法建立一個QrStyleOptions物件,QR碼生成邏輯使用該物件來應用使用者的偏好。 選項包括:
Color:這些屬性設定QR碼的背景和前景顏色,允許個性化外觀以符合品牌或美學偏好。Dimensions:此屬性確定QR碼尺寸,提供如何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
此過程檢查是否有生成的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
此靈活性允許使用者選擇最適合其需求的格式,無論是優化質量(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;
}
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
此方法重置參與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
此方法被應用程式不同部分所利用,以確保當發生錯誤時,能以清晰簡潔的資訊快速通知使用者。 例如,若在載入徽標或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
步驟5:運行應用程式
當應用程式被執行時,主窗口會如提供的圖像所展示的樣子出現。 佈局被整齊地組織成輸入、樣式、輸出和操作的區域。

過程中的第一步是在"輸入QR文字"字段中輸入資料。 這些資料將構成QR碼的內容,如URL或文字資訊。 接下來,為個性化QR碼,我們通過點擊"選擇徽標"按鈕來選擇一個徽標。 選擇後,徽標顯示在按鈕旁邊的預覽框中,確認其已整合到QR碼設計中。

在選擇徽標後,我們選擇QR碼的前景色和背景色。 點擊相應按鈕後所選顏色顯示在每個按鈕旁的顏色展示框中,立即確認我們的選擇。

對於此特定的QR碼,我們將尺寸設為500,確保程式碼符合我們的需求,邊距設為20,這提供了一個緩衝區,防止掃描問題。

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

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

保存後,成功資訊確認QR碼已成功儲存。

若我們需要重新開始或建立新的QR碼,點擊"重置表單"按鈕會將形式恢復到原始狀態,清除所有字段和選擇,準備好生成下個QR碼。

這是使用IronQR生成的已保存QR碼:

結論
總結來說,本指南已向您展示如何在C#應用程式中使用IronQR程式庫生成QR碼的過程。 通過從在Visual Studio中設置專案、整合IronQR程式庫、設計使用者友好介面以及編寫後端邏輯的步驟細分,我們證明了將QR碼功能新增到您的應用程式是多麼容易。
對於那些有興趣進一步探索IronQR功能的人,值得注意的是,IronQR提供免費試用以便您開始使用。 如果您決定將IronQR整合到您的專案中,授權開始於$999,為專業級QR碼生成提供了具成本效益的解決方案。
常見問題
如何在C#中建立一個QR Code生成器應用程式?
要在C#中建立QR Code生成器應用程式,首先在Visual Studio中設置Windows Forms應用程式。通過NuGet安裝IronQR程式庫,設計介面包括文字、標誌和顏色的輸入欄,然後使用IronQR的方法實現QR Code生成的邏輯。
C#中QR Code的客製化選項有哪些?
IronQR提供QR Code的客製化選項,例如更改顏色、尺寸和邊距。您還可以通過調整QrStyleOptions物件中的設置向QR Code新增標誌。
如何在C#專案中安裝QR Code程式庫?
在Visual Studio中使用NuGet Package Manager將IronQR程式庫安裝到您的C#專案中。搜索IronQR並點擊“安裝”按鈕將其新增到專案中。
在C#中我可以使用什麼格式來儲存生成的QR Code?
使用IronQR,您可以將生成的QR Code儲存為多種格式,包括PNG和JPEG,以提供在質量和文件大小方面的靈活性。
我可以使用C#程式庫讀取QR Code嗎?
是的,IronQR包含讀取QR Code的功能,使您能夠有效地解碼並提取QR圖片中的資料。
使用C# QR Code程式庫的好處是什麼?
像IronQR這樣的C# QR Code程式庫簡化了QR Code生成和讀取的過程,提供多格式支持、客製化選項以及與各種.NET版本的相容性。
如何在C#中處理生成QR Code時的錯誤?
可以通過在C#中使用try-catch塊將錯誤處理整合到您的QR Code生成應用程式中。這確保在QR Code建立過程中的任何問題都能順利處理,提供使用者友好的反饋。
我需要授權才能在C#應用程式中使用QR Code程式庫嗎?
是的,為了無限制使用IronQR,您需要有效的授權金鑰。初始測試可使用試用版本,全面使用則可購買專業授權。
如何在C#中將標誌嵌入QR Code中?
使用IronQR,您可以通過在QrStyleOptions物件中設置標誌圖片將標誌嵌入QR Code中。這使您能夠用品牌元素來個性化QR Code。
運行C# QR Code生成器應用程式的步驟是什麼?
在設置和客製化您的C# QR Code生成器應用程式後,只需在Visual Studio中運行應用程式,生成QR Code,並使用提供的選項將其儲存為您所需的格式。




