使用 IRONQR 如何在 C# 中創建 QR 碼生成器應用程序 Jordi Bardia 更新:2026年1月18日 下載 IronQR NuGet 下載 開始免費試用 LLM副本 LLM副本 將頁面複製為 Markdown 格式,用於 LLMs 在 ChatGPT 中打開 請向 ChatGPT 諮詢此頁面 在雙子座打開 請向 Gemini 詢問此頁面 在 Grok 中打開 向 Grok 詢問此頁面 打開困惑 向 Perplexity 詢問有關此頁面的信息 分享 在 Facebook 上分享 分享到 X(Twitter) 在 LinkedIn 上分享 複製連結 電子郵件文章 歡迎閱讀我們使用 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的一些主要特點 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); } $vbLabelText $csharpLabel 我們使用以下二維碼進行掃描: 我們得到了以下輸出結果: 過程首先合併必要的命名空間 IronQr 和 IronSoftware.Drawing,並特別提及 Color,該命名空間來自 IronSoftware.Drawing,用於處理圖像操作。 在開始讀取二維碼之前,必須使用您的許可證金鑰啟動軟體,方法是將其分配給 IronQr.License.LicenseKey。 然後,程式碼繼續使用 AnyBitmap.FromFile("QRCode.png") 從檔案載入二維碼圖片。 圖片載入完畢後,下一步是準備進行二維碼偵測。 此準備工作是透過建立一個 QrImageInput 物件來完成的,該物件用作映像的容器。 此功能的核心在於 QrReader 類,該類被實例化並用於執行二維碼讀取操作。 閱讀器分析準備好的圖像 qrInput,尋找其中包含的任何二維碼。 此操作的結果是一組 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); $vbLabelText $csharpLabel 讀取高級二維碼 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}"); } } $vbLabelText $csharpLabel 這是使用IronQR掃描二維碼後的輸出結果: 我們使用以下二維碼: 每個 QrResult 物件提供圖像中二維碼的解碼資料 (Value)、任何嵌入的 URL (Url) 和空間座標 (Points) 的存取。 IronQR會為檢測到的每個二維碼提供詳細信息,包括二維碼中的確切內容和任何 URL。 此外,該庫還提供了圖像中二維碼角點的精確座標(透過 Points 屬性)。 若要在 C# 應用程式中使用IronQR二維碼庫建立二維碼產生器,請仔細按照下列步驟操作。 本指南將引導您完成設定 Windows 窗體應用程式、安裝IronQR庫、編寫產生二維碼的程式碼以及了解輸出結果的過程。 步驟 1:在 Visual Studio 中建立 Windows 應用程式 首先,在您的電腦上啟動 Visual Studio。 點擊"建立新項目"按鈕。 選擇"Windows 窗體應用程式"作為專案類型。 請務必選擇 C# 作為程式語言。 輸入項目名稱並選擇儲存位置。 然後在下一個畫面上,選擇.NET Framework。 然後點選"創建" 。 它將在 Visual Studio 中建立並開啟一個 Windows 窗體應用程式。 步驟 2:安裝IronQR庫 現在是時候在專案中安裝IronQR庫了。 您可以透過不同的方法安裝IronQR庫。 選擇符合您喜好的選項: 使用NuGet套件管理器進行安裝 在解決方案資源管理器中以滑鼠右鍵按一下您的項目,然後選擇"管理NuGet套件" 。 在搜尋框中輸入IronQR ,然後按 Enter 鍵。 在清單中找到IronQR ,然後點選旁邊的"安裝" 。 使用NuGet套件管理器控制台進行安裝 前往"工具" > "NuGet套件管理員" > "套件管理員控制台" 。 輸入Install-Package IronQR並按 Enter 鍵。 步驟三:設計前端 3.1 標題頁眉 啟動二維碼產生器應用程式後,用戶會立即看到一個醒目的標題"QR Generator IronQR",字體粗體且權威。 字體 Agency FB 因其簡潔現代的線條而被選中,給人一種高效和精準的感覺。 標題採用醒目的 48 號字體,既突出又有力,能夠吸引用戶的注意力,並牢牢確立應用程式的身份。 3.2 輸入部分 二維碼文字輸入 輸入部分的核心是一個簡單而基本的元件:文字輸入框。 在這裡,使用者可以輸入他們想要編碼到二維碼中的資料。 這個框空間很大,可以容納大量文字,而且位置顯眼,靠近頂部。 標誌選擇 在文字輸入框下方,"選擇徽標"區域允許進行額外的自訂設定。 用戶可以上傳徽標,該徽標將嵌入二維碼中,從而增強品牌識別度或個人化二維碼。 旁邊的圖片框提供了所選徽標的預覽,提供即時的視覺回饋。 色彩配置 向右移動,介面會顯示顏色選擇選項。 兩個按鈕,一個用於設定二維碼顏色,另一個用於設定背景顏色,使用戶能夠自訂二維碼的調色板。 這些按鈕旁邊的富文本方塊顯示目前選定的顏色。 輸入部分的佈局經過精心設計,包括文字、徽標和顏色選項,體現了在創建二維碼時對使用者優先事項的清晰理解。 它兼具功能性和靈活性,使用戶能夠快速且有效率地輸入必要訊息,同時也為創造力提供了空間。 3.3 樣式參數 尺寸設定 在顏色自訂工具旁邊,使用者可以找到"尺寸"輸入框。這個數值設定至關重要,因為它決定了二維碼的整體大小,確保它能完美地適應預期的顯示環境,無論是名片、傳單還是電子螢幕。 邊距設定 在尺寸輸入框旁邊,"邊距"欄位可讓使用者指定二維碼周圍的空白區域。 頁邊距不僅僅是一種美觀的選擇;它是一個功能性元素,會影響掃描器對二維碼的讀取。 該應用程式提供了一個數值上下控制按鈕,方便使用者輕鬆調整此參數。 3.4 輸出預覽 使用者啟動二維碼產生後,表單左側標示"輸出"的大圖片框就成為焦點。 它可以作為動態顯示屏,即時預覽產生的二維碼。 這種即時的視覺回饋對於使用者驗證他們的設計選擇並確保二維碼符合他們的預期,然後再保存,至關重要。 3.5 操作按鈕 產生二維碼 "產生二維碼"按鈕是應用程式介面中的關鍵控制元素。 此按鈕位於表單的戰略位置,是產生二維碼過程的催化劑。 點擊此按鈕後,應用程式將取得使用者定義的所有輸入資料和樣式參數,並開始產生自訂二維碼。 儲存二維碼 產生二維碼並顯示在輸出預覽區域後,"儲存二維碼"按鈕即可生效。 點擊後,將開啟儲存對話框,允許使用者選擇所需的檔案格式和儲存位置。 重設表單 按一下此按鈕,即可清除所有先前的輸入和選擇,將所有設定還原為預設值。 這是該表單的一個重要方面,它提供了一種快速重新初始化應用程式的方法,而無需手動調整每個選項。 第四步:編寫後端邏輯 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; $vbLabelText $csharpLabel QR_Generator 類別的建構子在準備應用程式以供使用方面起著至關重要的作用。 應用程式的元件在此初始化,這是 Windows 窗體應用程式中設定窗體 UI 元素的標準步驟。 public QR_Generator() { InitializeComponent(); SetLicenseKey(); EnsureDirectoryExists(qrCodesDirectory); } public QR_Generator() { InitializeComponent(); SetLicenseKey(); EnsureDirectoryExists(qrCodesDirectory); } $vbLabelText $csharpLabel 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"; } $vbLabelText $csharpLabel 將 "YOUR_LICENSE_KEY" 替換為您從Iron Software取得的實際許可證金鑰。 此方法在 QR_Generator 類別的建構子中調用,確保在應用程式啟動時以及在生成任何二維碼之前立即套用許可證。 4.3 目錄管理 該應用程式使用 EnsureDirectoryExists 方法來檢查指定的用於儲存二維碼的目錄是否存在。 否則,它會建立該目錄。 此方法接受一個參數,即要檢查或建立的目錄的路徑。 以下是具體實現方式: 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); } } $vbLabelText $csharpLabel 此方法利用 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"); $vbLabelText $csharpLabel 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}"; } $vbLabelText $csharpLabel 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; } } $vbLabelText $csharpLabel 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); } } } $vbLabelText $csharpLabel 成功選擇圖像後,應用程式會嘗試載入該圖像並顯示預覽。 然後,將 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(); } $vbLabelText $csharpLabel 在 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); } } $vbLabelText $csharpLabel 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 }; } $vbLabelText $csharpLabel 此方法建立一個 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); } } } $vbLabelText $csharpLabel 此方法檢查是否存在已產生的二維碼。 如果是這樣,它會向使用者提供將檔案儲存為 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; } $vbLabelText $csharpLabel 這種靈活性使用戶能夠選擇最適合自己需求的格式,無論是優先考慮品質(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; } $vbLabelText $csharpLabel 此方法會重置二維碼生成過程中涉及的每個元件。 例如,它會清除二維碼文本,將尺寸和邊距設為預設值,並刪除任何選定的顏色或徽標。 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"); } $vbLabelText $csharpLabel 應用程式的不同部分都採用了這種方法,以確保在發生錯誤時,能夠及時向用戶發送清晰簡潔的訊息。 例如,如果在載入徽標或產生二維碼的過程中發生錯誤,應用程式會呼叫 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"); } } } $vbLabelText $csharpLabel 步驟 5:運行應用程式 應用程式運行時,主視窗將如圖所示顯示。 佈局清晰地分為輸入、樣式、輸出和操作四個部分。 第一步是將資料輸入到"輸入二維碼文字"欄位中。 這些資料將構成二維碼的內容,例如網址或文字資訊。 接下來,為了個人化二維碼,我們點擊"選擇標誌"按鈕來選擇一個標誌。 選取後,徽標會清晰地顯示在按鈕旁的預覽框中,確認已融入二維碼設計中。 選定標誌後,我們選擇二維碼的前景色和背景色。 點選對應的按鈕後,所選顏色會反映在每個按鈕旁的顏色顯示框中,讓我們立即看到所選顏色,從而得到直覺的確認。 對於這個特定的二維碼,我們將尺寸設為 500,以確保二維碼的大小符合我們的需求,並將邊距調整為 20,這樣可以在二維碼周圍留出緩衝區,以防止掃描問題。 所有輸入和樣式選項設定完畢後,我們點擊"產生二維碼"按鈕來產生二維碼。 應用程式處理我們的輸入,並在輸出圖片框中顯示新產生的二維碼。 要儲存產生的二維碼,我們只需點擊"儲存二維碼"按鈕。 此操作會開啟一個儲存對話框,讓我們可以選擇二維碼影像的目標位置和檔案格式。 儲存成功後,會顯示成功訊息,確認二維碼已成功儲存。 如果需要重新開始或建立新的二維碼,點擊"重置表單"按鈕會將表單恢復到原始狀態,清除所有欄位和選擇,為下一次二維碼產生做好準備。 這是IronQR產生的已儲存二維碼: 結論 總之,本指南已引導您完成在 C# 應用程式中使用IronQR庫產生二維碼的過程。 透過在 Visual Studio 中設定專案、整合IronQR庫、設計使用者友好的介面以及編寫後端邏輯等步驟,我們示範了為應用程式添加二維碼功能是多麼容易。 對於有興趣進一步探索IronQR功能的人來說,值得注意的是, IronQR提供免費試用版,幫助您入門。 如果您決定將IronQR整合到您的專案中,授權起價為 $799,為專業級二維碼產生提供經濟高效的解決方案。 常見問題解答 如何在 C# 中創建一個 QR 代碼生成器應用程式? 若要在 C# 中創建一個 QR 代碼生成器應用程式,從在 Visual Studio 中設置 Windows Forms 應用程式開始,通過 NuGet 安裝 IronQR 庫,設計包含文本、徽標和顏色輸入欄位的界面,然後使用 IronQR 的方法實現 QR 代碼生成邏輯。 在 C# 中,QR 代碼有哪些自定義選項? IronQR 為 QR 代碼提供自定義選項,如更改顏色、尺寸和邊距。您還可以通過調整 QrStyleOptions 對象中的設置來向 QR 代碼添加徽標。 如何在 C# 項目中安裝 QR 代碼庫? 使用 Visual Studio 中的 NuGet 包管理器在您的 C# 項目中安裝 IronQR 庫。搜索 IronQR 並點擊"安裝"按鈕以將其添加到您的項目中。 在 C# 中,我可以使用哪些格式保存生成的 QR 代碼? 使用IronQR,您可以將生成的QR碼保存為各種格式,包括PNG和JPEG,這使得在質量和檔案大小方面具有靈活性。 我可以使用 C# 庫讀取 QR 代碼嗎? 是的,IronQR 包含讀取 QR 代碼的功能,讓您能夠有效地解碼和提取 QR 圖像中的數據。 使用 C# QR 代碼庫有哪些好處? 像 IronQR 這樣的 C# QR 代碼庫簡化了生成和讀取 QR 代碼的過程,提供多格式支持、自定義選項以及與各種 .NET 版本的兼容性等功能。 如何在 C# 中處理生成 QR 代碼的錯誤? 錯誤處理可以通過在您的 QR 代碼生成應用程式中使用 try-catch 塊來進行。這可確保在 QR 代碼創建過程中發生的任何問題得到妥善管理,提供用戶友好的反饋。 我需要許可證才能在 C# 應用程式中使用 QR 代碼庫嗎? 是的,要無限制地使用 IronQR,您需要一個有效的許可證密鑰。可以提供試用版進行初步測試,專業許可證可供購買以獲得完全訪問。 我該如何在 C# 中將徽標整合到 QR 代碼中? 使用 IronQR,您可以通過在 QrStyleOptions 對象中設置徽標圖片來將徽標整合到 QR 代碼中。這使您能夠以品牌元素個性化 QR 代碼。 運行 C# 中的 QR 代碼生成器應用程式需要哪些步驟? 在 C# 中設置和自定義 QR 代碼生成器應用程式後,只需在 Visual Studio 中運行應用程式,生成 QR 代碼,並使用提供的選項將其保存為您想要的格式。 Jordi Bardia 立即與工程團隊聊天 軟體工程師 Jordi 在 Python、C# 和 C++ 上最得心應手,當他不在 Iron Software 展現技術時,便在做遊戲編程。在分担產品测测试,產品開發和研究的责任時,Jordi 為持续的產品改進增值。他说这种多样化的经验使他受到挑战并保持参与, 而这也是他与 Iron Software 中工作一大乐趣。Jordi 在佛罗里达州迈阿密长大,曾在佛罗里达大学学习计算机科学和统计学。 相關文章 更新2026年3月1日 QR Code .NET Core Generator & Reader | IronQR for .NET QR 碼 .NET Core 教學:使用 C# 中的 IronQR 生成 QR 碼、配置纠錯级别、添加徽標,并以 ML 供电的精度读取 QR 碼。 閱讀更多 更新2026年2月27日 如何使用NuGet套件在C#中生成QR代碼 安裝IronQR NuGet套件,並在幾分鐘內於C#中生成QR代碼。支持跨平台.NET 5-10,自訂樣式,PDF嵌入和機器學習增強閱讀。 閱讀更多 更新2026年3月1日 QR代碼.NET Core:在C#中讀取和生成QR代碼 學習使用IronQR在.NET Core中讀取和生成QR代碼。涵蓋機器學習增強的閱讀、錯誤更正級別、國際字符以及跨平台生成C#代碼示例。 閱讀更多 如何在 C# 中讀取 QR 碼如何在 .NET 6 中使用 QRCoder ...
更新2026年3月1日 QR Code .NET Core Generator & Reader | IronQR for .NET QR 碼 .NET Core 教學:使用 C# 中的 IronQR 生成 QR 碼、配置纠錯级别、添加徽標,并以 ML 供电的精度读取 QR 碼。 閱讀更多
更新2026年2月27日 如何使用NuGet套件在C#中生成QR代碼 安裝IronQR NuGet套件,並在幾分鐘內於C#中生成QR代碼。支持跨平台.NET 5-10,自訂樣式,PDF嵌入和機器學習增強閱讀。 閱讀更多
更新2026年3月1日 QR代碼.NET Core:在C#中讀取和生成QR代碼 學習使用IronQR在.NET Core中讀取和生成QR代碼。涵蓋機器學習增強的閱讀、錯誤更正級別、國際字符以及跨平台生成C#代碼示例。 閱讀更多