如何在 C# 中生成 QR 碼和條形碼

Generate QR Codes in C# - Complete Tutorial for .NET Developers

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

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

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

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

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

  1. 使用NuGet套件管理器安裝https://www.nuget.org/packages/BarCode

    PM > Install-Package BarCode
  2. 複製並運行這段程式碼。

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

    今天就在您的專案中開始使用免費試用IronBarcode

    arrow pointer

How Do I Install a QR Code Library in 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

How Can I Create a Simple QR Code in 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) -糾錯:確定在次優條件下的可讀性(低、中、四分位數或高)

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

使用C#中的IronBarcode產生的標準二維碼 一個包含"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的先進編碼功能。

How Do I Read QR Codes in 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# 中生成 QR 代碼?

您可以使用 IronBarcode 的 QRCodeWriter.CreateQrCode() 方法在 C# 中生成 QR 碼。此方法允許您傳递內容、大小和误差校正级别以有效创建 QR 碼。

QR 碼可以导出到哪些图像格式?

使用 IronBarcode,您可以将 QR 碼导出為多种格式,包括 PNG、JPEG、PDF 和 HTML。為此可以使用 SaveAsPng()SaveAsJpeg()SaveAsPdf()SaveAsHtmlFile() 方法。

如何将公司徽標添加到 QR 碼?

IronBarcode 提供 CreateQrCodeWithLogo() 方法,您可以傳递包含徽標图像的 QRCodeLogo 對象。該庫确保徽標尺寸和位置正确,以保持 QR 碼的可读性。

什么是 QR 碼误差校正,我應該選择哪個级别?

QR 碼中的误差校正即使部分损坏仍能保持可扫描性。IronBarcode 提供四個级别:低 (7%)、中 (15%)、四分位 (25%) 和高 (30%)。中是大多數用途合適的,而高適用于环境艰难的情况下。

如何验證自定义 QR 碼的可读性?

您可以使用 GeneratedBarcode 對象上的 Verify() 方法来确保自定义 QR 碼在進行诸如颜色更改或徽標添加等修改後仍然可扫描。

可以在 QR 碼中编碼二進制數据嗎?

是的,IronBarcode 的 CreateQrCode() 方法支持编碼字节數组,使您能够在 QR 碼中存储文件或加密內容等二進制數据。

如何從 C# 中的图像读取 QR 碼?

要從 C# 中的图像读取 QR 碼,请使用 IronBarcode 的 BarcodeReader.Read() 方法。為了优化性能,在 BarcodeReaderOptions 中指定 BarcodeEncoding.QRCode

QR 碼的最大數据容量是多少?

IronBarcode 生成的 QR 碼根据選择的误差校正级别可以容纳多达 2,953 字节、4,296 個字母數字字符或 7,089 個數字。

如何改变 QR 碼的颜色并确保其可扫描性?

IronBarcode 中的 ChangeBarCodeColor() 方法允許您改变 QR 碼的颜色。请务必在颜色更改後使用 Verify() 方法,以确保 QR 碼的可读性不受影响。

一個專业的 QR 碼庫有哪些特性?

IronQR 是 Iron Software 的專业庫,包括机器学习驱動的 QR 碼读取,准确率达 99.99%,并针對复杂應用的強大生成能力。

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

Jacob Mellor是Iron Software的首席技術官,也是開創C# PDF技術的前瞻性工程師。作為Iron Software核心代碼庫的原始開發者,他自公司成立以來就塑造了公司的產品架構,並與CEO Cameron Rimington將公司轉型為服務NASA、Tesla以及全球政府機構的50多人公司。

Jacob擁有曼徹斯特大學土木工程一級榮譽學士學位(1998年–2001年)。他於1999年在倫敦開立首家軟體公司,並於2005年建立了他的第一個.NET組件,專注於解決Microsoft生態系統中的複雜問題。

他的旗艦作品IronPDF和Iron Suite .NET程式庫全球已獲得超過3000萬次NuGet安裝,他的基礎代碼不斷在全球各地驅動開發者工具。擁有25年以上的商業經驗和41年的編碼專業知識,Jacob仍然專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。

準備好開始了嗎?
Nuget 下載 2,108,094 | 版本: 2026.3 剛剛發布
Still Scrolling Icon

還在捲動嗎?

想要快速證明? PM > Install-Package BarCode
執行範例 看您的字串變成 BarCode。