C# 二維碼產生器應用程式
歡迎閱讀我們使用 C# 建立二維碼的指南! 二維碼和 .NET 條碼 DLL 已成為快速且有效率地共享資訊的流行方式。 無論您是在開發應用程式、管理網站,還是只是想尋找一種簡潔的方式來分享鏈接,這些程式碼都非常有用。 在本指南中,我們將示範如何使用IronQR有效地產生二維碼,確保您可以產生符合您需求的二維碼。 這個函式庫讓任何使用 C# 的人都能輕鬆建立二維碼,而無需了解複雜的邏輯。 我們將一步一步地指導您,確保您擁有開始所需的一切。 無論您是想為您的應用程式添加二維碼生成器功能,還是只是好奇它是如何實現的,您都來對了地方。 我們開始吧。
如何在 C# 中建立二維碼產生器
- 在 Visual Studio 中建立一個 Windows Forms 應用程式
- 使用 NuGet 安裝 QR 函式庫
- 設計表單前端元素
- 編寫 QR 生成的邏輯
- 運行應用程式並開始創建 QR 代碼
在 C# 中安裝二維碼產生器庫
!{--01001100010010010100001001010010010000010101001001011001010111110101001101010100010001010101010 10100010111110101010001010010010010010100000101001100010111110100001001001100010011111010000100100110001001111010101
在開始之前,我們需要安裝IronQR NuGet 套件。
Install-Package IronQR
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 擅長解碼二維碼,為使用者提供了一種直接存取二維碼中嵌入資訊的方法。 您可以快速且準確地從二維碼中提取數據,從簡單的網址到複雜的嵌入式資訊。
:path=/static-assets/qr/content-code-examples/tutorials/csharp-qr-code-generator-application-1.csusing IronQr;
using IronSoftware.Drawing;
using System;
using System.Collections.Generic;
IronQr.License.LicenseKey = "License-Key";
// Load the image file that contains the QR Code
var inputImage = AnyBitmap.FromFile("QRCode.png");
// Prepare the image for QR code detection
QrImageInput qrInput = new QrImageInput(inputImage);
// Initialize the QR Code reader
QrReader qrReader = new QrReader();
// Execute QR Code reading on the provided image
IEnumerable<QrResult> qrResults = qrReader.Read(qrInput);
// Assuming you have the QR results in qrResults as before
foreach (var result in qrResults)
{
Console.WriteLine(result.Value); // Print the QR code content to the console
}Imports IronQr
Imports IronSoftware.Drawing
Imports System
Imports System.Collections.Generic
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)
' Assuming you have the QR results in qrResults as before
For Each result In qrResults
Console.WriteLine(result.Value) ' Print the QR code content to the console
Next result這個過程首先引入必要的命名空間:IronQr 和 IronSoftware.Drawing,其中特別提到了 IronSoftware.Drawing 命名空間中的 Color 來處理影像操作。
在開始讀取二維碼之前,必須使用許可證金鑰來啟動軟體,方法是將其分配給IronQr.License.LicenseKey 。 然後,程式碼繼續使用AnyBitmap.FromFile("QRCode.png")從檔案載入 QR 碼映像。
圖片載入完畢後,下一步是準備進行二維碼偵測。 此準備工作是透過建立QrImageInput物件來完成的,該物件用作影像的容器。
此功能的核心在於QrReader類,該類別被實例化並用於執行二維碼讀取操作。 閱讀器會分析準備好的圖像,尋找其中包含的任何二維碼。 這個操作的結果是一個QrResult物件集合,每個物件代表影像中偵測到的一個二維碼。
為了存取和使用二維碼中編碼的數據,該程式碼使用foreach循環遍歷結果集合。每個QrResult物件都包含諸如二維碼值之類的屬性,這些屬性可以被存取和顯示。
自訂二維碼讀取模式選項
IronQR 提供不同的二維碼讀取模式,可滿足各種不同的需求。
-混合掃描模式:兼顧速度和準確性,適用於不清晰或部分隱藏的二維碼。 -機器學習 (ML) 掃描模式:採用先進技術讀取損壞或難以讀取的二維碼,非常適合難以檢測的場景。 -基本掃描模式:最簡單快速的方式,可掃描清晰明了的二維碼。
:path=/static-assets/qr/content-code-examples/tutorials/csharp-qr-code-generator-application-2.csusing IronQr;
using IronQr.Enum;
using IronSoftware.Drawing;
using System.Collections.Generic;
IronQr.License.LicenseKey = "License-Key";
// Load the image file that contains the QR Code
var inputImage = AnyBitmap.FromFile("QRCode.png");
QrImageInput mixedScanInput = new QrImageInput(inputImage, QrScanMode.OnlyDetectionModel);
IEnumerable<QrResult> mixedScanResults = new QrReader().Read(mixedScanInput);
QrImageInput mlScanInput = new QrImageInput(inputImage, QrScanMode.OnlyDetectionModel);
IEnumerable<QrResult> mlScanResults = new QrReader().Read(mlScanInput);
QrImageInput basicScanInput = new QrImageInput(inputImage, QrScanMode.OnlyBasicScan);
IEnumerable<QrResult> basicScanResults = new QrReader().Read(basicScanInput);Imports IronQr
Imports IronQr.Enum
Imports IronSoftware.Drawing
Imports System.Collections.Generic
IronQr.License.LicenseKey = "License-Key"
' Load the image file that contains the QR Code
Dim inputImage = AnyBitmap.FromFile("QRCode.png")
Dim mixedScanInput As New QrImageInput(inputImage, QrScanMode.OnlyDetectionModel)
Dim mixedScanResults As IEnumerable(Of QrResult) = (New QrReader()).Read(mixedScanInput)
Dim mlScanInput As New QrImageInput(inputImage, QrScanMode.OnlyDetectionModel)
Dim mlScanResults As IEnumerable(Of QrResult) = (New QrReader()).Read(mlScanInput)
Dim basicScanInput As New QrImageInput(inputImage, QrScanMode.OnlyBasicScan)
Dim basicScanResults As IEnumerable(Of QrResult) = (New QrReader()).Read(basicScanInput)讀取高級二維碼
IronQR 先進的二維碼讀取功能為二維碼掃描和解碼提供了一種全面的方法。 此功能集超越了基本的閱讀功能,提供了更深層的互動和資料擷取。
:path=/static-assets/qr/content-code-examples/tutorials/csharp-qr-code-generator-application-3.csusing IronQr;
using IronSoftware.Drawing;
using System;
using System.Collections.Generic;
IronQr.License.LicenseKey = "License-Key";
var imageToScan = AnyBitmap.FromFile("QRCode.png");
QrImageInput qrInput = new QrImageInput(imageToScan);
QrReader qrScanner = new QrReader();
IEnumerable<QrResult> scanResults = qrScanner.Read(qrInput);
foreach (QrResult qrResult in scanResults)
{
Console.WriteLine(qrResult.Value);
Console.WriteLine(qrResult.Url);
foreach (IronSoftware.Drawing.PointF coordinate in qrResult.Points)
{
Console.WriteLine($"{coordinate.X}, {coordinate.Y}");
}
}Imports IronQr
Imports IronSoftware.Drawing
Imports System
Imports System.Collections.Generic
IronQr.License.LicenseKey = "License-Key"
Dim imageToScan = AnyBitmap.FromFile("QRCode.png")
Dim qrInput As New QrImageInput(imageToScan)
Dim qrScanner As New QrReader()
Dim scanResults As IEnumerable(Of QrResult) = qrScanner.Read(qrInput)
For Each qrResult As QrResult In scanResults
Console.WriteLine(qrResult.Value)
Console.WriteLine(qrResult.Url)
For Each coordinate As IronSoftware.Drawing.PointF In qrResult.Points
Console.WriteLine($"{coordinate.X}, {coordinate.Y}")
Next coordinate
Next qrResult若要在 C# 應用程式中使用 IronQR 庫建立二維碼產生器,請仔細按照下列步驟操作。 本指南將引導您完成設定 Windows 窗體應用程式、安裝 IronQR 程式庫、編寫產生二維碼的程式碼以及了解輸出結果的過程。
步驟 1:在 Visual Studio 中建立 Windows 應用程式
- 首先在您的電腦上啟動 Visual Studio。
- 點選"建立新項目"按鈕。
選擇"Windows 窗體應用程式"作為專案類型。 請務必選擇 C# 作為程式語言。
輸入項目名稱並選擇儲存位置。 然後在下一個畫面上,選擇 .NET 框架。 然後點選"創建" 。
步驟 2:安裝 IronQR 庫
現在是時候在專案中安裝 IronQR 庫了。 您可以透過不同的方法安裝 IronQR 庫。
使用 NuGet 套件管理器進行安裝
- 在解決方案資源管理器中以滑鼠右鍵按一下您的項目,然後選擇"管理 NuGet 套件" 。
- 在搜尋框中輸入
IronQR並按Enter 鍵。 管理 NuGet 套件 在清單中找到IronQR ,然後點選旁邊的"安裝" 。
使用 NuGet 套件管理器控制台進行安裝

Install-Package IronQR並按 Enter 鍵。
步驟三:設計前端

3.1 標題頁眉

啟動二維碼產生器應用程式後,用戶會立即看到一個醒目的標題"QR Generator IronQR",字體粗體且權威。
3.2 輸入部分
二維碼文字輸入
使用者可以輸入他們想要編碼到二維碼中的資料。
標誌選擇

"選擇徽標"區域允許進行更進階的自訂設定。 用戶可以上傳一個徽標,該徽標將嵌入到二維碼中。
色彩配置

顏色選擇按鈕可讓使用者自訂二維碼的調色板。
3.3 樣式參數

尺寸設定
允許使用者指定二維碼的整體尺寸。
邊距設定
允許使用者指定二維碼周圍的空白區域。
3.4 輸出預覽
提供產生的二維碼的即時預覽。

3.5 操作按鈕
產生二維碼
觸發二維碼產生過程。

儲存二維碼
開啟儲存對話框,用於儲存二維碼。

重設表單
清除之前的所有輸入和選擇。

第四步:編寫後端邏輯
4.1 設定和初始化
包含必要的命名空間:IronQR 和 IronSoftware.Drawing.
:path=/static-assets/qr/content-code-examples/tutorials/csharp-qr-code-generator-application-4.csusing IronQr;
using IronSoftware.Drawing;
using Color = IronSoftware.Drawing.Color;
Imports IronQr
Imports IronSoftware.Drawing
Imports Color = IronSoftware.Drawing.Color:path=/static-assets/qr/content-code-examples/tutorials/csharp-qr-code-generator-application-5.cspublic 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 Sub4.2 許可證密鑰配置
應用IronQR庫的有效許可證金鑰:
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請將"YOUR_LICENSE_KEY"替換為您的實際許可證密鑰。
4.3 目錄管理
檢查或建立必要的目錄。
:path=/static-assets/qr/content-code-examples/tutorials/csharp-qr-code-generator-application-7.csprivate 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 SubQR_Generator 類別建構子中定義了 QR 碼目錄的路徑,即 qrCodesDirectory,它將應用程式的啟動路徑與"QR Codes"資料夾名稱組合在一起:
:path=/static-assets/qr/content-code-examples/tutorials/csharp-qr-code-generator-application-8.csstring qrCodesDirectory = System.IO.Path.Combine(Application.StartupPath, "QR Codes");Dim qrCodesDirectory As String = System.IO.Path.Combine(Application.StartupPath, "QR Codes")4.4 顏色選擇
提供顏色對話框組件和實用功能。
:path=/static-assets/qr/content-code-examples/tutorials/csharp-qr-code-generator-application-9.csprivate 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 FunctionUpdateColor方法接受選定的顏色,並使用十六進位字串將其轉換為IronSoftware.Drawing.Color格式,並根據選擇更新二維碼的前景色或背景色。 它還會更新使用者介面以反映新的顏色選擇:
:path=/static-assets/qr/content-code-examples/tutorials/csharp-qr-code-generator-application-10.csprivate 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 Sub4.5 新增徽標
允許使用者選擇徽標。
:path=/static-assets/qr/content-code-examples/tutorials/csharp-qr-code-generator-application-11.csprivate 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 Sub4.6 二維碼生成
包含根據使用者輸入產生二維碼的邏輯。
:path=/static-assets/qr/content-code-examples/tutorials/csharp-qr-code-generator-application-12.csprivate void btn_generate_Click(object sender, EventArgs e)
{
GenerateQRCode();
}Private Sub btn_generate_Click(ByVal sender As Object, ByVal e As EventArgs)
GenerateQRCode()
End SubQrOptions物件定義了糾錯級別,增強了二維碼對損壞或遮蔽的抵抗力。 CreateStyleOptions方法產生一個QrStyleOptions對象,其中包含使用者的自訂設置,例如顏色、尺寸和標誌。 方法詳述如下:
:path=/static-assets/qr/content-code-examples/tutorials/csharp-qr-code-generator-application-14.csprivate 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 Function4.7 儲存二維碼
負責保存產生的二維碼。
:path=/static-assets/qr/content-code-examples/tutorials/csharp-qr-code-generator-application-15.csprivate 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:path=/static-assets/qr/content-code-examples/tutorials/csharp-qr-code-generator-application-16.csprivate 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 Function4.8 重置應用程式
清除使用者輸入並重設表單狀態。
:path=/static-assets/qr/content-code-examples/tutorials/csharp-qr-code-generator-application-17.csprivate void btn_reset_Click(object sender, EventArgs e)
{
ResetFields();
}
private void ResetFields()
{
txt_QR.Text = string.Empty;
txt_dimension.Value = 200;
txt_margin.Value = 0;
bgColor = Color.White;
color = Color.Black;
txt_selected_color.BackColor = System.Drawing.Color.White;
txt_selected_bgcolor.BackColor = System.Drawing.Color.Black;
logoBmp = null;
selected_logo.Image = null;
pictureBox.Image = null;
}Private Sub btn_reset_Click(ByVal sender As Object, ByVal e As EventArgs)
ResetFields()
End Sub
Private Sub ResetFields()
txt_QR.Text = String.Empty
txt_dimension.Value = 200
txt_margin.Value = 0
bgColor = Color.White
color = Color.Black
txt_selected_color.BackColor = System.Drawing.Color.White
txt_selected_bgcolor.BackColor = System.Drawing.Color.Black
logoBmp = Nothing
selected_logo.Image = Nothing
pictureBox.Image = Nothing
End Sub4.9 錯誤處理
向使用者顯示錯誤訊息。
:path=/static-assets/qr/content-code-examples/tutorials/csharp-qr-code-generator-application-18.csprivate 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 Sub4.10 完整程式碼範例
包含以上所有功能的完整程式碼可以在連結到您專案的範例文件中找到。
:path=/static-assets/qr/content-code-examples/tutorials/csharp-qr-code-generator-application-19.csusing 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:運行應用程式
應用程式運行時,主視窗會顯示為分為輸入、樣式、輸出和操作等部分。 依照使用者介面輸入數據,自訂二維碼,並根據需要產生和儲存二維碼。
結論
總而言之,本指南已引導您完成在 C# 應用程式中使用 IronQR 庫產生二維碼的過程。 透過在 Visual Studio 中設定專案、整合 IronQR 庫、設計使用者友好的介面以及編寫後端邏輯等步驟,我們示範了為應用程式添加二維碼功能是多麼容易。
對於有興趣進一步探索 IronQR 功能的人來說,值得注意的是,IronQR 提供免費試用版,幫助您入門。 如果您決定將 IronQR 整合到您的專案中,授權起價為$799 ,為專業級二維碼產生提供經濟高效的解決方案。
常見問題解答
如何在 C# 中創建二維碼生成器應用程式?
要在 C# 中創建二維碼生成器應用程式,可以使用 IronQR 庫。首先在 Visual Studio 中設置 Windows Forms 應用程式,通過 NuGet 安裝 IronQR,設計應用程式的前端。使用 IronQR 的功能實現二維碼生成邏輯,例如顏色選擇和徽標嵌入。
.NET 二維碼庫的優勢是什麼?
.NET 二維碼庫如 IronQR 提供高級功能,例如高準確度讀取二維碼、生成二維碼的自訂選項,並支持各種 .NET 環境。它還允許二維碼調整大小和樣式。
如何在 C# 中處理二維碼生成時的錯誤?
在 C# 中,可以通過使用 try-catch 塊實施適當的錯誤處理機制來處理二維碼生成期間的錯誤。IronQR 有助於平滑的錯誤管理,確保在二維碼創建過程中出現的任何問題得到高效解決。
我可以使用二維碼庫將徽標嵌入到二維碼中嗎?
是的,您可以使用 IronQR 庫將徽標嵌入到二維碼中。此功能允許您通過將自定義徽標納入設計來增強二維碼的品牌化。
如何保存 C# 應用程式中生成的二維碼?
您可以使用 IronQR 的功能指定存儲目錄來保存 C# 應用程式中生成的二維碼。這允許您高效管理和存儲應用程式內生成的二維碼。
配置二維碼庫的許可密鑰需要哪些步驟?
要配置 IronQR 的許可密鑰,您需要在應用程式中整合許可代碼。這通常涉及添加 IronQR 提供的特定代碼行,以使用購買的許可激活庫。
如何在 C# 應用程式中使用特定顏色樣式化二維碼?
IronQR 允許您通過使用其顏色自訂功能來為二維碼設置樣式。您可以使用集成到應用程式中的顏色選擇對話框選擇二維碼的前景和背景顏色。
在 Visual Studio 中安裝二維碼庫的過程是什麼?
要在 Visual Studio 中安裝像 IronQR 這樣的二維碼庫,請使用 NuGet 套件管理器。搜索 'IronQR' 並點擊 'Install',將其添加到專案中。或者,使用套件管理器控制台使用命令 'Install-Package IronQR'。





