如何在C#中生成二维码和条形码

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

Need to generate QR codes in your C# application? This tutorial shows you exactly how to create, customize, and verify QR codes using IronBarcode—from simple one-line implementations to advanced features like logo embedding and binary data encoding.

Whether you're building inventory systems, event ticketing platforms, or contactless payment solutions, you'll learn how to implement professional-grade QR code functionality in your .NET applications.

Quickstart: One-Line QR Code Creation with IronBarcode

Ready to generate a QR Code fast? Here’s how you can use IronBarcode’s QRCodeWriter API to produce a QR code in just one line of code—customization is optional but powerful.

Nuget IconGet started making PDFs with NuGet now:

  1. Install IronBarcode with NuGet Package Manager

    PM > Install-Package BarCode

  2. Copy and run this code snippet.

    var qr = QRCodeWriter.CreateQrCode("https://ironsoftware.com/", 500, QRCodeWriter.QrErrorCorrectionLevel.Medium); qr.SaveAsPng("MyQR.png");
  3. Deploy to test on your live environment

    Start using IronBarcode in your project today with a free trial
    arrow pointer

How Do I Install a QR Code Library in C#?

今天在您的项目中使用 IronBarcode,免费试用。

第一步:
green arrow pointer

Install IronBarcode using the NuGet Package Manager with this simple command:

Install-Package BarCode

Install via NuGet

Alternatively, download the IronBarcode DLL directly and add it as a reference to your project.

Import Required Namespaces

Add these namespaces to access IronBarcode's QR code generation features:

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

How Can I Create a Simple QR Code in C#?

Generate a QR code with just one line of code using IronBarcode's CreateQrCode method:

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");
Imports IronBarCode

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

The CreateQrCode method accepts three parameters:

  • Text content: The data to encode (supports URLs, text, or any string data)
  • Size: Pixel dimensions for the square QR code (500x500 in this example)
  • Error correction: Determines readability in suboptimal conditions (Low, Medium, Quartile, or High)

Higher error correction levels enable QR codes to remain readable even when partially damaged or obscured, though they result in denser patterns with more data modules.

Standard QR code generated with IronBarcode in C# A basic QR code containing "hello world" text, generated at 500x500 pixels with medium error correction

How Do I Add a Logo to My QR Code?

Embedding logos in QR codes enhances brand recognition while maintaining scannability. IronBarcode automatically positions and sizes logos to preserve QR code integrity:

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");
Imports IronBarCode
Imports IronSoftware.Drawing

' Load logo image
Private qrCodeLogo As New QRCodeLogo("visual-studio-logo.png")

' Create QR code with embedded logo
Private myQRCodeWithLogo As GeneratedBarcode = 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

The CreateQrCodeWithLogo method intelligently handles logo placement by:

  • Automatically sizing the logo to maintain QR code readability
  • Positioning it within the quiet zone to avoid data corruption
  • Preserving the logo's original colors when changing QR code colors

This approach ensures your branded QR codes remain fully functional across all scanning devices and applications.

QR code with embedded Visual Studio logo QR code featuring the Visual Studio logo, demonstrating IronBarcode's automatic logo sizing and positioning

How Can I Export QR Codes to Different Formats?

IronBarcode supports multiple export formats for different use cases. Export your QR codes as images, PDFs, or HTML files:

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
Imports IronBarCode
Imports System.Drawing

' Create QR code with logo
Private qrCodeLogo As New QRCodeLogo("visual-studio-logo.png")
Private myQRCodeWithLogo As GeneratedBarcode = 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

Each format serves specific purposes:

  • PDF: Ideal for printable documents and reports
  • HTML: Perfect for web integration without external dependencies
  • PNG/JPEG: Standard image formats for versatile usage

How Do I Verify QR Code Readability After Customization?

Color modifications and logo additions can impact QR code scannability. Use the Verify() method to ensure your customized QR codes remain readable:

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");

// Open in default browser
System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo
{
    FileName = "MyVerifiedQR.html",
    UseShellExecute = true
});
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");

// Open in default browser
System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo
{
    FileName = "MyVerifiedQR.html",
    UseShellExecute = true
});
Imports IronBarCode
Imports IronSoftware.Drawing
Imports System
Imports System.Drawing

' Generate QR code with logo
Private qrCodeLogo As New QRCodeLogo("visual-studio-logo.png")
Private myVerifiedQR As GeneratedBarcode = 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 Not myVerifiedQR.Verify() Then
	Console.WriteLine("LightBlue is not dark enough to be read accurately. Let's try DarkBlue")
	myVerifiedQR.ChangeBarCodeColor(Color.DarkBlue)
End If

' Save verified QR code
myVerifiedQR.SaveAsHtmlFile("MyVerifiedQR.html")

' Open in default browser
System.Diagnostics.Process.Start(New System.Diagnostics.ProcessStartInfo With {
	.FileName = "MyVerifiedQR.html",
	.UseShellExecute = True
})
$vbLabelText   $csharpLabel

The Verify() method performs a comprehensive scan test on your QR code. This ensures compatibility across different scanning devices and lighting conditions before deployment.

Verified QR code with dark blue coloring and Visual Studio logo A successfully verified QR code in dark blue, demonstrating proper contrast for reliable scanning

How Can I Encode Binary Data in QR Codes?

QR codes excel at storing binary data efficiently. This capability enables advanced applications like encrypted data transfer, file sharing, and IoT device configuration:

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");
}
Imports IronBarCode
Imports System
Imports System.Linq

' Convert string to binary data
Private binaryData() As Byte = 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
Dim myReturnedData = BarcodeReader.Read("MyBinaryQR.png").First()

' Confirm data matches original
If binaryData.SequenceEqual(myReturnedData.BinaryValue) Then
	Console.WriteLine("Binary Data Read and Written Perfectly")
Else
	Throw New Exception("Data integrity check failed")
End If
$vbLabelText   $csharpLabel

Binary encoding in QR codes offers several advantages:

  • Efficiency: Stores data in compact binary format
  • Versatility: Handles any data type (files, encrypted content, serialized objects)
  • Integrity: Preserves exact byte sequences without encoding issues

This feature distinguishes IronBarcode from basic QR code libraries, enabling sophisticated data exchange scenarios in your applications.

QR code containing binary encoded data QR code storing binary data, demonstrating IronBarcode's advanced encoding capabilities

How Do I Read QR Codes in C#?

IronBarcode provides flexible QR code reading capabilities. Here's the simplest approach:

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.");
}
Imports IronBarCode
Imports System
Imports System.Linq

' Read QR code with optimized settings
Private result As BarcodeResults = BarcodeReader.Read("QR.png", New BarcodeReaderOptions() With {.ExpectBarcodeTypes = BarcodeEncoding.QRCode})

' Extract and display the decoded value
If result IsNot Nothing AndAlso result.Any() Then
	Console.WriteLine(result.First().Value)
Else
	Console.WriteLine("No QR codes found in the image.")
End If
$vbLabelText   $csharpLabel

For more complex scenarios requiring fine-tuned control:

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);
Imports IronBarCode
Imports System
Imports System.Linq

' Configure advanced reading options
Private options As New BarcodeReaderOptions With {
	.Speed = ReadingSpeed.Faster,
	.ExpectMultipleBarcodes = False,
	.ExpectBarcodeTypes = BarcodeEncoding.QRCode,
	.Multithreaded = True,
	.MaxParallelThreads = 4,
	.RemoveFalsePositive = True,
	.ImageFilters = New ImageFilterCollection() From {
		New AdaptiveThresholdFilter(),
		New ContrastFilter(),
		New SharpenFilter()
	}
}

' Read with advanced configuration
Private result As BarcodeResults = BarcodeReader.Read("QR.png", options)
$vbLabelText   $csharpLabel

These advanced reading options enable reliable QR code detection in challenging conditions like poor lighting, image distortion, or low-quality prints.

What's Next for QR Code Development?

Now that you've mastered QR code generation with IronBarcode, explore these advanced topics:

Download Resources

Access the complete source code and examples:

API Documentation

Explore the complete feature set in the API reference:

Alternative: IronQR for Advanced QR Applications

For projects requiring cutting-edge QR code capabilities, consider IronQR--Iron Software's specialized QR code library featuring machine learning-powered reading with 99.99% accuracy and advanced generation options.

Ready to implement QR codes in your .NET application? Start your free trial or download IronBarcode today.

常见问题解答

如何在 C# 中生成 QR 码?

你可以在C#中使用IronBarcode的QRCodeWriter.CreateQrCode()方法生成二维码。此方法允许你传递内容、尺寸和纠错级别以高效地创建二维码。

二维码可以导出为哪些图像格式?

使用IronBarcode,你可以将二维码导出为多种格式,包括PNG、JPEG、PDF和HTML。方法如SaveAsPng()SaveAsJpeg()SaveAsPdf()SaveAsHtmlFile()可用于此目的。

如何将公司Logo添加到二维码中?

IronBarcode提供CreateQrCodeWithLogo()方法,你可以传递包含Logo图像的QRCodeLogo对象。该库确保Logo尺寸和位置正确,以保持二维码可读性。

什么是二维码错误校正,应该选择哪个级别?

二维码中的错误校正使其即使在部分损坏时仍可扫描。IronBarcode提供四个级别:低(7%)、中(15%)、四分之一(25%)和高(30%)。中适用于大多数用途,而高在具有挑战性的环境中是理想的选择。

如何验证定制二维码的可读性?

你可以在GeneratedBarcode对象上使用Verify()方法,以确保你的定制二维码在进行颜色变化或Logo添加后的修改后仍然可扫描。

可以在二维码中编码二进制数据吗?

是的,IronBarcode的CreateQrCode()方法支持编码字节数组,使你能够在二维码中存储二进制数据,例如文件或加密内容。

如何在C#中从图像读取二维码?

要在C#中从图像读取二维码,请使用IronBarcode的BarcodeReader.Read()方法。为了优化性能,指定BarcodeEncoding.QRCodeBarcodeReaderOptions中。

二维码的最大数据容量是多少?

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 库在全球已获得超过 3000 万次的 NuGet 安装,其基础代码继续为全球使用的开发者工具提供支持。拥有 25 年商业经验和 41 年编程经验的 Jacob 仍专注于推动企业级 C#、Java 和 Python PDF 技术的创新,同时指导下一代技术领导者。

准备开始了吗?
Nuget 下载 1,935,276 | 版本: 2025.11 刚刚发布