如何在 C# 中建立二維碼產生器應用程式
歡迎閱讀我們使用 C# 建立二維碼的指南! 二維碼和 .NET 條碼 DLL 已成為快速且有效率地共享資訊的流行方式。 無論您是在開發應用程式、管理網站,還是只是想尋找一種簡潔的方式來分享鏈接,這些程式碼都非常有用。 在本指南中,我們將示範如何使用IronQR有效地產生二維碼,確保您可以產生符合您需求的二維碼。 這個函式庫讓任何使用 C# 的人都能輕鬆建立二維碼,而無需了解複雜的邏輯。 我們將一步一步地指導您,確保您擁有開始所需的一切。 無論您是想為您的應用程式添加二維碼生成器功能,還是只是好奇它是如何實現的,您都來對了地方。 我們開始吧。
如何在 C# 中建立二維碼產生器
- 在 Visual Studio 中建立一個 Windows 窗體應用程式
- 使用 NuGet 安裝 QR 函式庫
- 設計表單前端元素
- 編寫二維碼生成邏輯
- 運行應用程式並開始建立二維碼
IronQR:C# 二維碼庫
IronQR是一個 C# 二維碼庫,用於將二維碼功能整合到 .NET 應用程式中。 IronQR 支援多種 .NET 版本和專案類型,包括 C#、VB.NET、F#、.NET Core、.NET Standard、.NET Framework 等,可確保與 Windows、Linux、macOS、iOS 和 Android 等各種開發環境相容。
IronQR 的一些主要特點
IronQR 的功能不僅限於基本的二維碼生成,還提供多種功能,旨在滿足各種與二維碼相關的任務。 讓我們一起來了解這些功能並查看它們的範例程式碼,您可以將這些程式碼整合到任何類型的 .NET 應用程式範本中,例如控制台應用程式。
讀取二維碼
IronQR 擅長解碼二維碼,為使用者提供了一種直接存取二維碼中嵌入資訊的方法。 您可以快速且準確地從二維碼中提取數據,從簡單的網址到複雜的嵌入式資訊。
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);
}我們使用以下二維碼進行掃描:
如何在 C# 中建立二維碼產生器應用程式:圖 1 - 二維碼 PNG 圖像文件
我們得到了以下輸出結果:
如何在 C# 中建立二維碼產生器應用程式:圖 2 - 讀取二維碼輸出
過程首先引入必要的命名空間IronQr和IronSoftware.Drawing ,並特別提及IronSoftware.Drawing命名空間中的Color來處理影像操作。
在開始讀取二維碼之前,必須使用許可證金鑰來啟動軟體,方法是將其分配給IronQr.License.LicenseKey 。 然後,程式碼繼續使用AnyBitmap.FromFile("QRCode.png")從檔案載入 QR 碼映像。
圖片載入完畢後,下一步是準備進行二維碼偵測。 此準備工作是透過建立QrImageInput物件來完成的,該物件用作影像的容器。
此功能的核心在於QrReader類,該類別被實例化並用於執行二維碼讀取操作。 閱讀器分析準備好的圖像qrInput ,尋找其中包含的任何二維碼。 這個操作的結果是一個QrResult物件集合,每個物件代表影像中偵測到的一個二維碼。
為了存取和使用二維碼中編碼的數據,該程式碼使用foreach循環遍歷結果集合。每個QrResult物件都包含諸如二維碼值之類的屬性,這些屬性可以被存取和顯示。
自訂二維碼讀取模式選項
IronQR 提供多種從影像中讀取二維碼的方式,使其能夠滿足各種不同的需求。 其中一個選擇是混合掃描模式,它兼顧速度和準確性,當二維碼不清晰或部分被遮蔽時非常有用。
另一種是機器學習(ML)掃描模式,它利用智慧技術讀取損壞或通常不易讀取的二維碼。 這種模式非常適合二維碼難以偵測的複雜情況。
最後,還有基本掃描模式,是掃描清晰簡潔的二維碼最快、最簡單的方法。 當您需要快速獲得結果且二維碼易於讀取時,它是最佳選擇。
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);讀取高級二維碼
IronQR 的先進二維碼讀取功能旨在為二維碼掃描和解碼提供全面而細緻的方法。 此功能集超越了基本的二維碼讀取功能,提供了更深層的互動和資料擷取。
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 掃描二維碼後的輸出結果:
如何在 C# 中建立二維碼產生器應用程式:圖 3 - 掃描二維碼輸出
我們使用以下二維碼:
如何在 C# 中建立二維碼產生器應用程式:圖 4 - 二維碼輸入
每個QrResult物件提供對圖像中二維碼的解碼資料( Value )、任何嵌入的 URL( Url )和空間座標( Points )的存取。
IronQR 會為檢測到的每個二維碼提供詳細信息,包括二維碼中的確切內容和任何 URL。 此外,該庫還提供了圖像中二維碼角點的精確座標(透過Points屬性)。
若要在 C# 應用程式中使用 IronQR 二維碼庫建立二維碼產生器,請仔細按照下列步驟操作。 本指南將引導您完成設定 Windows 窗體應用程式、安裝 IronQR 程式庫、編寫產生二維碼的程式碼以及了解輸出結果的過程。
步驟 1:在 Visual Studio 中建立 Windows 應用程式
首先,在您的電腦上啟動 Visual Studio。 點擊"建立新項目"按鈕。
選擇"Windows 窗體應用程式"作為專案類型。 請務必選擇 C# 作為程式語言。
輸入項目名稱並選擇儲存位置。 然後在下一個畫面上,選擇 .NET 框架。 然後點選"創建" 。
它將在 Visual Studio 中建立並開啟一個 Windows 窗體應用程式。
步驟 2:安裝 IronQR 庫
現在是時候在專案中安裝 IronQR 庫了。 您可以透過不同的方法安裝 IronQR 庫。 選擇符合您喜好的選項:
使用 NuGet 套件管理器進行安裝
- 在解決方案資源管理器中以滑鼠右鍵按一下您的項目,然後選擇"管理 NuGet 套件" 。
在搜尋框中輸入IronQR ,然後按 Enter 鍵。
在清單中找到IronQR ,然後點選旁邊的"安裝" 。
使用 NuGet 套件管理器控制台進行安裝
- 前往"工具" > "NuGet 套件管理員" > "套件管理員控制台" 。
如何在 C# 中建立二維碼產生器應用程式:圖 9 - NuGet 套件管理器
輸入Install-Package IronQR並按 Enter 鍵。
步驟三:設計前端
如何在 C# 中建立二維碼產生器應用程式:圖 11 - 二維碼產生器
3.1 標題頁眉
如何在 C# 中建立二維碼產生器應用程式:圖 12 - 產生二維碼
啟動二維碼產生器應用程式後,用戶會立即看到一個醒目的標題"QR Generator IronQR",字體粗體且權威。 字體 Agency FB 因其簡潔現代的線條而被選中,給人一種高效和精準的感覺。 標題採用醒目的 48 號字體,既突出又有力,能夠吸引用戶的注意力,並牢牢確立應用程式的身份。
3.2 輸入部分
二維碼文字輸入
如何在 C# 中建立二維碼產生器應用程式:圖 13 - 二維碼文字輸入
輸入部分的核心是一個簡單而基本的元件:文字輸入框。 在這裡,使用者可以輸入他們想要編碼到二維碼中的資料。 這個框空間很大,可以容納大量文字,而且位置顯眼,靠近頂部。
標誌選擇
如何在 C# 中建立二維碼產生器應用程式:圖 14 - 選擇徽標
在文字輸入框下方,"選擇徽標"區域允許進行額外的自訂設定。 用戶可以上傳徽標,該徽標將嵌入二維碼中,從而增強品牌識別度或個人化二維碼。 旁邊的圖片框提供了所選徽標的預覽,提供即時的視覺回饋。
色彩配置
如何在 C# 中建立二維碼產生器應用程式:圖 15 - 背景顏色
向右移動,介面會顯示顏色選擇選項。 兩個按鈕,一個用於設定二維碼顏色,另一個用於設定背景顏色,使用戶能夠自訂二維碼的調色板。 這些按鈕旁邊的富文本方塊顯示目前選定的顏色。
輸入部分的佈局經過精心設計,包括文字、徽標和顏色選項,體現了在創建二維碼時對使用者優先事項的清晰理解。 它兼具功能性和靈活性,使用戶能夠快速且有效率地輸入必要訊息,同時也為創造力提供了空間。
3.3 樣式參數
如何在 C# 中建立二維碼產生器應用程式:圖 16 - 樣式
尺寸設定
在顏色自訂工具旁邊,使用者可以找到"尺寸"輸入框。這個數值設定至關重要,因為它決定了二維碼的整體大小,確保它能完美地適應預期的顯示環境,無論是名片、傳單還是電子螢幕。
邊距設定
在尺寸輸入框旁邊,"邊距"欄位可讓使用者指定二維碼周圍的空白區域。 頁邊距不僅僅是一種美觀的選擇;它是一個功能性元素,會影響掃描器對二維碼的讀取。 該應用程式提供了一個數值上下控制按鈕,方便使用者輕鬆調整此參數。
3.4 輸出預覽
如何在 C# 中建立二維碼產生器應用程式:圖 17 - 二維碼輸出
使用者啟動二維碼產生後,表單左側標示"輸出"的大圖片框就成為焦點。 它可以作為動態顯示屏,即時預覽產生的二維碼。 這種即時的視覺回饋對於使用者驗證他們的設計選擇並確保二維碼符合他們的預期,然後再保存,至關重要。
3.5 操作按鈕
產生二維碼
如何在 C# 中建立二維碼產生器應用程式:圖 18 - C# 中的二維碼
"產生二維碼"按鈕是應用程式介面中的關鍵控制元素。 此按鈕位於表單的戰略位置,是產生二維碼過程的催化劑。 點擊此按鈕後,應用程式將取得使用者定義的所有輸入資料和樣式參數,並開始產生自訂二維碼。
儲存二維碼
如何在 C# 中建立二維碼產生器應用程式:圖 19 - 儲存
產生二維碼並顯示在輸出預覽區域後,"儲存二維碼"按鈕即可生效。 點擊後,將開啟儲存對話框,允許使用者選擇所需的檔案格式和儲存位置。
重設表單
如何在 C# 中建立二維碼產生器應用程式:圖 20 - 重置
按一下此按鈕,即可清除所有先前的輸入和選擇,將所有設定還原為預設值。 這是該表單的一個重要方面,它提供了一種快速重新初始化應用程式的方法,而無需手動調整每個選項。
第四步:編寫後端邏輯
4.1 設定和初始化
首先,應用程式開始包含必要的命名空間: IronQr和IronSoftware.Drawing 。 這些命名空間至關重要,因為它們提供了在應用程式中產生和操作二維碼和顏色所需的功能。 自訂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;QR_Generator類別的建構函式在準備應用程式以供使用方面起著至關重要的作用。 應用程式的元件在此初始化,這是 Windows 窗體應用程式中設定窗體 UI 元素的標準步驟。
public QR_Generator()
{
InitializeComponent();
SetLicenseKey();
EnsureDirectoryExists(qrCodesDirectory);
}public QR_Generator()
{
InitializeComponent();
SetLicenseKey();
EnsureDirectoryExists(qrCodesDirectory);
}SetLicenseKey:呼叫此方法為 IronQR 函式庫套用有效的許可證金鑰。 對於商業應用,必須使用許可證金鑰才能解鎖 IronQR 庫的全部功能。EnsureDirectoryExists:鑑於需要儲存產生的二維碼,此方法可確保存在專用目錄。 它會檢查應用程式啟動路徑中是否存在"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";
}將"YOUR_LICENSE_KEY"替換為您從Iron Software獲得的實際許可證密鑰。 此方法在QR_Generator類別的建構子中調用,確保在應用程式啟動時以及在生成任何二維碼之前立即套用許可證。
4.3 目錄管理
該應用程式使用EnsureDirectoryExists方法檢查用於儲存二維碼的指定目錄是否存在。 否則,它會建立該目錄。 此方法接受一個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);
}
}此方法利用System.IO命名空間與檔案系統進行互動。 它首先使用Directory.Exists檢查指定路徑下的目錄是否存在。 如果目錄不存在(傳回false ),則使用Directory.CreateDirectory建立目錄。
QR_Generator類別建構函式中定義了 QR 碼目錄的路徑,即qrCodesDirectory ,它將應用程式的啟動路徑與"QR Codes"資料夾名稱結合:
string qrCodesDirectory = System.IO.Path.Combine(Application.StartupPath, "QR Codes");string qrCodesDirectory = System.IO.Path.Combine(Application.StartupPath, "QR Codes");4.4 顏色選擇
該應用程式在使用者介面上提供了兩個按鈕,每個按鈕都與一種選擇顏色的方法相關聯: 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方法接受選定的顏色,並使用十六進位字串將其轉換為IronSoftware.Drawing.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 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中,QR 生成邏輯稍後會使用該影像。
4.6 二維碼生成
當使用者點擊"生成"按鈕時,生成過程開始,該按鈕與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;
}此方法會重置二維碼生成過程中涉及的每個元件。 例如,它會清除二維碼文本,將尺寸和邊距設為預設值,並刪除任何選定的顏色或徽標。
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");
}應用程式的不同部分都採用了這種方法,以確保在發生錯誤時,能夠及時向用戶發送清晰簡潔的訊息。 例如,如果在載入徽標或產生二維碼的過程中發生錯誤,應用程式會呼叫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:運行應用程式
應用程式運行時,主視窗將如圖所示顯示。 佈局清晰地分為輸入、樣式、輸出和操作四個部分。
如何在 C# 中建立二維碼產生器應用程式:圖 21 - 應用程式輸出
第一步是將資料輸入到"輸入二維碼文字"欄位中。 這些資料將構成二維碼的內容,例如網址或文字資訊。 接下來,為了個人化二維碼,我們點擊"選擇標誌"按鈕來選擇一個標誌。 選取後,徽標會清晰地顯示在按鈕旁的預覽框中,確認已融入二維碼設計中。
如何在 C# 中建立二維碼產生器應用程式:圖 22 - Logo
選定標誌後,我們選擇二維碼的前景色和背景色。 點選對應的按鈕後,所選顏色會反映在每個按鈕旁的顏色顯示框中,讓我們立即看到所選顏色,從而得到直覺的確認。
如何在 C# 中建立二維碼產生器應用程式:圖 23 - 顏色選擇
對於這個特定的二維碼,我們將尺寸設為 500,以確保二維碼的大小符合我們的需求,並將邊距調整為 20,這樣可以在二維碼周圍留出緩衝區,以防止掃描問題。
如何在 C# 中建立二維碼產生器應用程式:圖 24 - 尺寸
所有輸入和樣式選項設定完畢後,我們點擊"產生二維碼"按鈕來產生二維碼。 應用程式處理我們的輸入,並在輸出圖片框中顯示新產生的二維碼。
如何在 C# 中建立二維碼產生器應用程式:圖 25 - 讀取二維碼輸出
要儲存產生的二維碼,我們只需點擊"儲存二維碼"按鈕。 此操作會開啟一個儲存對話框,讓我們可以選擇二維碼影像的目標位置和檔案格式。
如何在 C# 中建立二維碼產生器應用程式:圖 26 - 儲存對話框
儲存成功後,會顯示成功訊息,確認二維碼已成功儲存。
如何在 C# 中建立二維碼產生器應用程式:圖 27 - 成功訊息
如果需要重新開始或建立新的二維碼,點擊"重置表單"按鈕會將表單恢復到原始狀態,清除所有欄位和選擇,為下一次二維碼產生做好準備。
如何在 C# 中建立二維碼產生器應用程式:圖 28 - 重設表單
以下是IronQR產生的已儲存二維碼:
結論
總而言之,本指南已引導您完成在 C# 應用程式中使用 IronQR 庫產生二維碼的過程。 透過在 Visual Studio 中設定專案、整合 IronQR 庫、設計使用者友好的介面以及編寫後端邏輯等步驟,我們示範了為應用程式添加二維碼功能是多麼容易。
對於有興趣進一步探索 IronQR 功能的人來說,值得注意的是,IronQR 提供免費試用版,幫助您入門。 如果您決定將 IronQR 整合到您的專案中,授權起價為$799 ,為專業級二維碼產生提供經濟高效的解決方案。
常見問題解答
如何使用 C# 建立一個二維碼產生器應用程式?
要在 C# 中建立一個二維碼產生器應用程序,首先在 Visual Studio 中建立一個 Windows 窗體應用程式。透過 NuGet 安裝 IronQR 函式庫,設計包含文字、標誌和色彩輸入欄位的介面,然後使用 IronQR 的方法實作二維碼產生邏輯。
C#中二維碼有哪些自訂選項?
IronQR 提供二維碼自訂選項,例如更改顏色、尺寸和邊距。您也可以透過調整QrStyleOptions物件中的設置,為二維碼新增徽標。
如何在 C# 專案中安裝二維碼庫?
使用 Visual Studio 中的 NuGet 套件管理器將 IronQR 庫安裝到您的 C# 專案中。搜尋 IronQR,然後按一下「安裝」按鈕將其新增至您的專案。
在 C# 中,我可以使用哪些格式儲存產生的二維碼?
使用 IronQR,您可以將產生的二維碼儲存為各種格式,包括 PNG 和 JPEG,從而在品質和檔案大小方面提供靈活性。
我可以使用 C# 函式庫讀取二維碼嗎?
是的,IronQR 包含讀取二維碼的功能,使您能夠有效地解碼和提取二維碼影像中的資料。
使用 C# 二維碼庫有哪些好處?
AC# QR 程式碼庫(如 IronQR)簡化了產生和讀取 QR 程式碼的過程,提供了多格式支援、自訂選項以及與各種 .NET 版本的兼容性等功能。
如何在C#中處理產生二維碼時出現的錯誤?
在 C# 中使用 try-catch 程式碼區塊,可以將錯誤處理功能整合到二維碼產生應用程式中。這樣可以確保二維碼創建過程中出現的任何問題都能妥善處理,並提供用戶友好的回饋。
我在 C# 應用程式中使用二維碼庫需要許可證嗎?
是的,要無限制地使用 IronQR,您需要一個有效的許可證金鑰。我們提供試用版供您初步測試,您也可以購買專業版授權以獲得完整存取權限。
如何使用 C# 將徽標整合到二維碼中?
使用 IronQR,您可以透過在QrStyleOptions物件中設定徽標圖像,將徽標整合到二維碼中。這樣,您就可以使用品牌元素個人化二維碼。
如何在 C# 中運行二維碼產生器應用程式?
在 C# 中設定和自訂 QR 碼產生器應用程式後,只需在 Visual Studio 中執行應用程序,產生 QR 碼,然後使用提供的選項將其儲存為所需的格式。









