如何在 C# 中產生二維碼和條碼

使用 C# 產生二維碼 - .NET 開發人員完整教學

This article was translated from English: Does it need improvement?
Translated
View the article in English

需要在 C# 應用程式中產生二維碼嗎? 本教學將向您展示如何使用 IronBarcode 建立、自訂和驗證二維碼——從簡單的單行實現到高級功能,例如徽標嵌入和二進位資料編碼。

無論您是建立庫存系統、活動票務平台還是非接觸式支付解決方案,您都將學習如何在 .NET 應用程式中實現專業級二維碼功能。

快速入門:使用 IronBarcode 建立一行二維碼

想快速產生二維碼嗎?以下是如何使用 IronBarcode 的QRCodeWriter API,只需一行程式碼即可產生二維碼——自訂是可選的,但功能強大。

Nuget Icon立即開始使用 NuGet 建立 PDF 檔案:

  1. 使用 NuGet 套件管理器安裝 IronBarcode

    PM > Install-Package BarCode

  2. 複製並運行這段程式碼。

    var qr = QRCodeWriter.CreateQrCode("https://ironsoftware.com/", 500, QRCodeWriter.QrErrorCorrectionLevel.Medium); qr.SaveAsPng("MyQR.png");
  3. 部署到您的生產環境進行測試

    立即開始在您的專案中使用 IronBarcode,免費試用!
    arrow pointer

如何在C#中安裝二維碼庫?

使用 NuGet 套件管理器,透過以下簡單指令安裝 IronBarcode:

Install-Package BarCode

透過 NuGet 安裝

或者,直接下載 IronBarcode DLL並將其作為引用添加到您的專案中。

導入所需的命名空間

增加以下命名空間即可存取 IronBarcode 的二維碼產生功能:

using IronBarCode;
using System;
using System.Drawing;
using System.Linq;
using IronBarCode;
using System;
using System.Drawing;
using System.Linq;
$vbLabelText   $csharpLabel

如何在C#中建立簡單的二維碼?

使用 IronBarcode 的CreateQrCode方法,只需一行程式碼即可產生二維碼:

using IronBarCode;

// Generate a QR code with text content
var qrCode = QRCodeWriter.CreateQrCode("hello world", 500, QRCodeWriter.QrErrorCorrectionLevel.Medium);
qrCode.SaveAsPng("MyQR.png");
using IronBarCode;

// Generate a QR code with text content
var qrCode = QRCodeWriter.CreateQrCode("hello world", 500, QRCodeWriter.QrErrorCorrectionLevel.Medium);
qrCode.SaveAsPng("MyQR.png");
$vbLabelText   $csharpLabel

CreateQrCode方法接受三個參數:

-文字內容:要編碼的資料(支援 URL、文字或任何字串資料) -尺寸:方形二維碼的像素尺寸(本例為 500x500) -糾錯:確定在次優條件下的可讀性(低、中、四分位數或高)

更高的糾錯等級使二維碼即使在部分損壞或被遮蔽的情況下也能保持可讀性,但這會導致更密集的圖案和更多的資料模組。

使用 IronBarcode 在 C# 中產生標準二維碼 一個包含"hello world"文字的基本二維碼,尺寸為500x500像素,採用中等錯誤等級產生。

如何在二維碼中加入Logo?

在二維碼中嵌入徽標可以增強品牌識別度,同時保持可掃描性。 IronBarcode 會自動調整徽標的位置和大小,以保持二維碼的完整性:

using IronBarCode;
using IronSoftware.Drawing;

// Load logo image
QRCodeLogo qrCodeLogo = new QRCodeLogo("visual-studio-logo.png");

// Create QR code with embedded logo
GeneratedBarcode myQRCodeWithLogo = QRCodeWriter.CreateQrCodeWithLogo("https://ironsoftware.com/", qrCodeLogo);

// Customize appearance
myQRCodeWithLogo.ResizeTo(500, 500).SetMargins(10).ChangeBarCodeColor(Color.DarkGreen);

// Save the branded QR code
myQRCodeWithLogo.SaveAsPng("myQRWithLogo.png");
using IronBarCode;
using IronSoftware.Drawing;

// Load logo image
QRCodeLogo qrCodeLogo = new QRCodeLogo("visual-studio-logo.png");

// Create QR code with embedded logo
GeneratedBarcode myQRCodeWithLogo = QRCodeWriter.CreateQrCodeWithLogo("https://ironsoftware.com/", qrCodeLogo);

// Customize appearance
myQRCodeWithLogo.ResizeTo(500, 500).SetMargins(10).ChangeBarCodeColor(Color.DarkGreen);

// Save the branded QR code
myQRCodeWithLogo.SaveAsPng("myQRWithLogo.png");
$vbLabelText   $csharpLabel

CreateQrCodeWithLogo方法透過以下方式智慧處理標誌放置:

  • 自動調整標誌大小,以保持二維碼的可讀性
  • 將其放置在靜默區內,以避免資料損壞
  • 更改二維碼顏色時,請保持徽標的原始顏色不變

這種方法可以確保您的品牌二維碼在所有掃描設備和應用程式上都能完全正常運作。

帶有嵌入式 Visual Studio 標誌的二維碼 包含 Visual Studio 標誌的二維碼,展示了 IronBarcode 的自動標誌尺寸調整和位置功能。

如何將二維碼匯出為不同格式?

IronBarcode支援多種匯出格式,以滿足不同的使用情境。 將您的二維碼匯出為圖片、PDF 或 HTML 檔案:

using IronBarCode;
using System.Drawing;

// Create QR code with logo
QRCodeLogo qrCodeLogo = new QRCodeLogo("visual-studio-logo.png");
GeneratedBarcode myQRCodeWithLogo = QRCodeWriter.CreateQrCodeWithLogo("https://ironsoftware.com/", qrCodeLogo);

// Apply custom styling
myQRCodeWithLogo.ChangeBarCodeColor(Color.DarkGreen);

// Export to multiple formats
myQRCodeWithLogo.SaveAsPdf("MyQRWithLogo.pdf");      // PDF document
myQRCodeWithLogo.SaveAsHtmlFile("MyQRWithLogo.html"); // Standalone HTML
myQRCodeWithLogo.SaveAsPng("MyQRWithLogo.png");       // PNG image
myQRCodeWithLogo.SaveAsJpeg("MyQRWithLogo.jpg");      // JPEG image
using IronBarCode;
using System.Drawing;

// Create QR code with logo
QRCodeLogo qrCodeLogo = new QRCodeLogo("visual-studio-logo.png");
GeneratedBarcode myQRCodeWithLogo = QRCodeWriter.CreateQrCodeWithLogo("https://ironsoftware.com/", qrCodeLogo);

// Apply custom styling
myQRCodeWithLogo.ChangeBarCodeColor(Color.DarkGreen);

// Export to multiple formats
myQRCodeWithLogo.SaveAsPdf("MyQRWithLogo.pdf");      // PDF document
myQRCodeWithLogo.SaveAsHtmlFile("MyQRWithLogo.html"); // Standalone HTML
myQRCodeWithLogo.SaveAsPng("MyQRWithLogo.png");       // PNG image
myQRCodeWithLogo.SaveAsJpeg("MyQRWithLogo.jpg");      // JPEG image
$vbLabelText   $csharpLabel

每種格式都有其特定的用途:

  • PDF :非常適合用於列印文件和報告
  • HTML :非常適合無需外部相依性的 Web 集成
  • PNG/JPEG :用途廣泛的標準影像格式

定製完成後如何驗證二維碼的可讀性?

顏色修改和添加徽標可能會影響二維碼的掃描效果。 使用Verify()方法確保您的自訂二維碼仍然可讀:

using IronBarCode;
using IronSoftware.Drawing;
using System;
using System.Drawing;

// Generate QR code with logo
QRCodeLogo qrCodeLogo = new QRCodeLogo("visual-studio-logo.png");
GeneratedBarcode myVerifiedQR = QRCodeWriter.CreateQrCodeWithLogo("https://ironsoftware.com/", qrCodeLogo);

// Apply light color (may affect readability)
myVerifiedQR.ChangeBarCodeColor(Color.LightBlue);

// Verify the QR code can still be scanned
if (!myVerifiedQR.Verify())
{
    Console.WriteLine("LightBlue is not dark enough to be read accurately. Let's try DarkBlue");
    myVerifiedQR.ChangeBarCodeColor(Color.DarkBlue);
}

// Save verified QR code
myVerifiedQR.SaveAsHtmlFile("MyVerifiedQR.html");
using IronBarCode;
using IronSoftware.Drawing;
using System;
using System.Drawing;

// Generate QR code with logo
QRCodeLogo qrCodeLogo = new QRCodeLogo("visual-studio-logo.png");
GeneratedBarcode myVerifiedQR = QRCodeWriter.CreateQrCodeWithLogo("https://ironsoftware.com/", qrCodeLogo);

// Apply light color (may affect readability)
myVerifiedQR.ChangeBarCodeColor(Color.LightBlue);

// Verify the QR code can still be scanned
if (!myVerifiedQR.Verify())
{
    Console.WriteLine("LightBlue is not dark enough to be read accurately. Let's try DarkBlue");
    myVerifiedQR.ChangeBarCodeColor(Color.DarkBlue);
}

// Save verified QR code
myVerifiedQR.SaveAsHtmlFile("MyVerifiedQR.html");
$vbLabelText   $csharpLabel

Verify()方法會對你的二維碼執行全面的掃描測試。 這樣可以確保在部署前,不同掃描設備和光照條件下的兼容性。

已驗證的二維碼,採用深藍色和 Visual Studio 標誌一個已成功驗證的深藍色二維碼,對比度良好,可確保可靠掃描。

如何在二維碼中編碼二進位資料?

二維碼在高效儲存二進位資料方面表現出色。 此功能支援加密資料傳輸、檔案共享和物聯網裝置配置等進階應用:

using IronBarCode;
using System;
using System.Linq;

// Convert string to binary data
byte[] binaryData = System.Text.Encoding.UTF8.GetBytes("https://ironsoftware.com/csharp/barcode/");

// Create QR code from binary content
QRCodeWriter.CreateQrCode(binaryData, 500).SaveAsPng("MyBinaryQR.png");

// Read and verify binary data integrity
var myReturnedData = BarcodeReader.Read("MyBinaryQR.png").First();

// Confirm data matches original
if (binaryData.SequenceEqual(myReturnedData.BinaryValue))
{
    Console.WriteLine("Binary Data Read and Written Perfectly");
}
else
{
    throw new Exception("Data integrity check failed");
}
using IronBarCode;
using System;
using System.Linq;

// Convert string to binary data
byte[] binaryData = System.Text.Encoding.UTF8.GetBytes("https://ironsoftware.com/csharp/barcode/");

// Create QR code from binary content
QRCodeWriter.CreateQrCode(binaryData, 500).SaveAsPng("MyBinaryQR.png");

// Read and verify binary data integrity
var myReturnedData = BarcodeReader.Read("MyBinaryQR.png").First();

// Confirm data matches original
if (binaryData.SequenceEqual(myReturnedData.BinaryValue))
{
    Console.WriteLine("Binary Data Read and Written Perfectly");
}
else
{
    throw new Exception("Data integrity check failed");
}
$vbLabelText   $csharpLabel

二維碼中的二進位編碼具有以下幾個優點:

-效率:以緊湊的二進位格式儲存數據 -多功能性:可處理任何資料類型(檔案、加密內容、序列化物件) -完整性:保留精確的位元組序列,無編碼問題

此功能使 IronBarcode 與基本的二維碼庫區分開來,從而在您的應用程式中實現複雜的資料交換場景。

包含二進位編碼資料的二維碼 儲存二進位資料的二維碼,展示了IronBarcode的先進編碼功能。

如何在C#中讀取二維碼?

IronBarcode 提供靈活的二維碼讀取功能。 最簡單的方法如下:

using IronBarCode;
using System;
using System.Linq;

// Read QR code with optimized settings
BarcodeResults result = BarcodeReader.Read("QR.png", new BarcodeReaderOptions() { 
    ExpectBarcodeTypes = BarcodeEncoding.QRCode 
});

// Extract and display the decoded value
if (result != null && result.Any())
{
    Console.WriteLine(result.First().Value);
}
else
{
    Console.WriteLine("No QR codes found in the image.");
}
using IronBarCode;
using System;
using System.Linq;

// Read QR code with optimized settings
BarcodeResults result = BarcodeReader.Read("QR.png", new BarcodeReaderOptions() { 
    ExpectBarcodeTypes = BarcodeEncoding.QRCode 
});

// Extract and display the decoded value
if (result != null && result.Any())
{
    Console.WriteLine(result.First().Value);
}
else
{
    Console.WriteLine("No QR codes found in the image.");
}
$vbLabelText   $csharpLabel

對於需要精細控制的更複雜場景:

using IronBarCode;
using System;
using System.Linq;

// Configure advanced reading options
BarcodeReaderOptions options = new BarcodeReaderOptions
{
    Speed = ReadingSpeed.Faster,           // Optimize for speed
    ExpectMultipleBarcodes = false,        // Single QR code expected
    ExpectBarcodeTypes = BarcodeEncoding.QRCode, // QR codes only
    Multithreaded = true,                  // Enable parallel processing
    MaxParallelThreads = 4,                // Utilize multiple CPU cores
    RemoveFalsePositive = true,            // Filter out false detections
    ImageFilters = new ImageFilterCollection() // Apply preprocessing
    {
        new AdaptiveThresholdFilter(),    // Handle varying lighting
        new ContrastFilter(),              // Enhance contrast
        new SharpenFilter()                // Improve edge definition
    }
};

// Read with advanced configuration
BarcodeResults result = BarcodeReader.Read("QR.png", options);
using IronBarCode;
using System;
using System.Linq;

// Configure advanced reading options
BarcodeReaderOptions options = new BarcodeReaderOptions
{
    Speed = ReadingSpeed.Faster,           // Optimize for speed
    ExpectMultipleBarcodes = false,        // Single QR code expected
    ExpectBarcodeTypes = BarcodeEncoding.QRCode, // QR codes only
    Multithreaded = true,                  // Enable parallel processing
    MaxParallelThreads = 4,                // Utilize multiple CPU cores
    RemoveFalsePositive = true,            // Filter out false detections
    ImageFilters = new ImageFilterCollection() // Apply preprocessing
    {
        new AdaptiveThresholdFilter(),    // Handle varying lighting
        new ContrastFilter(),              // Enhance contrast
        new SharpenFilter()                // Improve edge definition
    }
};

// Read with advanced configuration
BarcodeResults result = BarcodeReader.Read("QR.png", options);
$vbLabelText   $csharpLabel

這些高級讀取選項能夠在光線不足、影像失真或印刷品質差等具有挑戰性的條件下可靠地檢測二維碼。

二維碼開發的下一步是什麼?

既然您已經掌握了使用 IronBarcode 產生二維碼,不妨探索以下進階主題:

-從PDF文件中提取二維碼 -實現批次二維碼處理 -對疑難掃描影像進行影像校正

下載資源

查看完整原始碼和範例:

API 文件

請參閱 API 參考文檔,以了解完整的功能集:

替代方案:IronQR,適用於進階二維碼應用

對於需要尖端二維碼功能的項目,請考慮使用IronQR ——Iron Software 的專業二維碼庫,具有機器學習驅動的讀取功能,準確率高達 99.99%,並提供高級生成選項。

準備好在您的 .NET 應用程式中實作二維碼了嗎? 立即開始免費試用下載 IronBarcode

常見問題解答

如何在C#中產生二維碼?

您可以使用IronBarcode's QRCodeWriter.CreateQrCode()方法在 C# 中產生二維碼。此方法可讓您傳遞內容、尺寸和糾錯級別,從而有效率地建立二維碼。

二維碼可以匯出為哪些影像格式?

使用 IronBarcode,您可以將二維碼匯出為多種格式,包括 PNG、JPEG、PDF 和 HTML。為此,您可以使用SaveAsPng()SaveAsJpeg()SaveAsPdf()SaveAsHtmlFile()等方法。

如何在二維碼中加入公司標誌?

IronBarcode 提供了CreateQrCodeWithLogo()方法,您可以透過該方法傳入一個包含標誌圖像的QRCodeLogo物件。該庫會確保徽標的大小和位置正確,從而確保二維碼清晰可讀。

什麼是二維碼糾錯?我應該選擇哪個級別?

二維碼的糾錯功能使其即使部分損壞也能保持可掃描性。 IronBarcode 提供四種糾錯等級:低 (7%)、中 (15%)、四分位數 (25%) 和高 (30%)。中級適用於大多數用途,而高級則非常適合嚴苛的環境。

如何驗證自訂二維碼的可讀性?

您可以使用GeneratedBarcode物件上的Verify()方法,以確保您的自訂二維碼在修改(例如顏色變更或新增標誌)後仍然可掃描。

二進位資料可以編碼到二維碼中嗎?

是的,IronBarcode 的CreateQrCode()方法支援對位元組數組進行編碼,允許您在二維碼中儲存二進位數據,例如檔案或加密內容。

如何在C#中讀取影像中的二維碼?

若要在 C# 中讀取影像中的二維碼,請使用 IronBarcode 的BarcodeReader.Read()方法。為了獲得最佳效能,請在BarcodeReaderOptions中指定BarcodeEncoding.QRCode

二維碼的最大資料容量是多少?

IronBarcode 產生的二維碼最多可容納 2,953 位元組、4,296 個字母數字字元或 7,089 個數字,具體取決於所選的糾錯等級。

如何在保持二維碼可掃描的前提下更改其顏色?

IronBarcode 中的ChangeBarCodeColor()方法可讓您變更二維碼的顏色。更改顏色後,請務必使用Verify()方法確認二維碼的可讀性不受影響。

專業二維碼庫提供哪些功能?

IronQR 是 Iron Software 的一個專用庫,包含高級功能,例如機器學習驅動的二維碼讀取,準確率高達 99.99%,以及專為複雜應用量身定制的強大生成功能。

Jacob Mellor,Team Iron 首席技術官
首席技術長

Jacob Mellor 是 Iron Software 的首席技術官,也是一位富有遠見的工程師,率先開發了 C# PDF 技術。作為 Iron Software 核心程式碼庫的最初開發者,他自公司成立之初便參與塑造了其產品架構,並與執行長 Cameron Rimington 一起將其發展成為一家擁有 50 多名員工、服務於 NASA、特斯拉和全球政府機構的公司。

Jacob 於 1998 年至 2001 年在曼徹斯特大學獲得土木工程一級榮譽學士學位。 1999 年,他在倫敦創辦了自己的第一家軟體公司;2005 年,他創建了自己的第一個 .NET 元件。此後,他專注於解決微軟生態系統中的複雜問題。

他的旗艦產品 IronPDF 和 IronSuite .NET 庫在全球 NuGet 上的安裝量已超過 3000 萬次,其基礎程式碼持續為全球開發者工具提供支援。憑藉 25 年的商業經驗和 41 年的程式設計專長,Jacob 始終致力於推動企業級 C#、Java 和 Python PDF 技術的創新,同時指導下一代技術領導者。

準備好開始了嗎?
Nuget 下載 2,035,202 | 版本: 2025.12 剛剛發布