Saltar al pie de página
USANDO IRONQR

Cómo leer QR desde una imagen en C#

QR codes (Quick Response Codes) are everywhere—on product packaging, event tickets, menus, and even business cards. As a .NET developer, being able to quickly and reliably read QR codes from images can open the door to powerful automation and user interaction features. In this guide, we’ll walk you through how to use IronQR, a high-performance QR code library built specifically for .NET, to read QR codes from images with just a few lines of C# code.

Whether you’re building inventory management software, integrating two-factor authentication, or simply decoding URLs from screenshots, IronQR makes it easy.

What is IronQR?

IronQR is a powerful C# QR code library developed to create a powerful QR code reader and writer for .NET developers. IronQR is designed for both QR code generation and scanning, and it supports reading from a variety of image formats, making it ideal for use in desktop, web, or server applications. Through this library, you can create accurate QR code reader tools to automate the entire process of QR code recognition and reading.

Key Features

  • Read and generate QR codes with ease.
  • Support for JPEG, PNG, BMP, and other image formats.
  • High-speed performance and accurate detection for easy extraction of QR code data.
  • Works across .NET Framework, .NET Core, .NET Standard (2.0+), and .NET 6/7+ projects.
  • Offers cross-platform support, so you can work in your preferred app environment and operating system, whether that's Windows, Linux, or any other supported environment.

Unlike open-source alternatives, IronQR focuses on enterprise-grade stability, commercial licensing, and professional support—making it an excellent fit for business-critical applications.

Setting Up IronQR in Your C# Project

Before you can start scanning QR codes, let’s walk through how to set up IronQR in your .NET application.

Install via NuGet

You can install IronQR directly from the NuGet Package Manager Console:

Install-Package IronQR
Install-Package IronQR
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'Install-Package IronQR
$vbLabelText   $csharpLabel

Alternatively, use the NuGet GUI in Visual Studio by searching for IronQR, and click "Install":

How Read QR From Image in C#: Figure 2 - IronQR NuGet Package Manager screen

Add Namespaces and Basic Setup

Once installed, include the following namespace in your C# file:

using IronSoftware.Drawing;
using IronQR;
using IronSoftware.Drawing;
using IronQR;
Imports IronSoftware.Drawing
Imports IronQR
$vbLabelText   $csharpLabel

Note: IronSoftware.Drawing is used for handling image formats in a cross-platform manner.

Read QR Code from an Image

Let’s dive into how to actually read a QR code from a file using IronQR.

Supported Image Formats

IronQR supports multiple types of image formats, including:

  • PNG
  • JPG/JPEG
  • BMP
  • GIF
  • TIFF

This flexibility allows you to work with virtually any image source, from camera snapshots to scanned documents.

Basic Code Example

Let's take a closer look at how you can use this library to decode QR codes with ease. Here’s a minimal example that reads a single QR code with the text value "Hello World!" from an image file, using the Bitmap class and a file stream to load the image:

using IronQr;
using IronSoftware.Drawing;
using System;
class Program
{
    static void Main()
    {
        // Load the image using a file stream
        using var stream = File.OpenRead("sample-qr.png");
        var bitmapImage = AnyBitmap.FromStream(stream);
        QrImageInput qrImageInput = new QrImageInput(bitmapImage );
        // Read the QR code
        QrReader qrReader = new QrReader();
        try
        {
     // Use the QR read method to read the values within your QR code(s)
            IEnumerable<QrResult> results = qrReader.Read(qrImageInput);
            // Output the decoded value
            foreach (var result in results)
            {
                Console.WriteLine("QR Code Value: " + result.Value);
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error reading QR code: " + ex.Message);
        }
    }
}
using IronQr;
using IronSoftware.Drawing;
using System;
class Program
{
    static void Main()
    {
        // Load the image using a file stream
        using var stream = File.OpenRead("sample-qr.png");
        var bitmapImage = AnyBitmap.FromStream(stream);
        QrImageInput qrImageInput = new QrImageInput(bitmapImage );
        // Read the QR code
        QrReader qrReader = new QrReader();
        try
        {
     // Use the QR read method to read the values within your QR code(s)
            IEnumerable<QrResult> results = qrReader.Read(qrImageInput);
            // Output the decoded value
            foreach (var result in results)
            {
                Console.WriteLine("QR Code Value: " + result.Value);
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error reading QR code: " + ex.Message);
        }
    }
}
Imports IronQr
Imports IronSoftware.Drawing
Imports System
Friend Class Program
	Shared Sub Main()
		' Load the image using a file stream
		Dim stream = File.OpenRead("sample-qr.png")
		Dim bitmapImage = AnyBitmap.FromStream(stream)
		Dim qrImageInput As New QrImageInput(bitmapImage)
		' Read the QR code
		Dim qrReader As New QrReader()
		Try
	 ' Use the QR read method to read the values within your QR code(s)
			Dim results As IEnumerable(Of QrResult) = qrReader.Read(qrImageInput)
			' Output the decoded value
			For Each result In results
				Console.WriteLine("QR Code Value: " & result.Value)
			Next result
		Catch ex As Exception
			Console.WriteLine("Error reading QR code: " & ex.Message)
		End Try
	End Sub
End Class
$vbLabelText   $csharpLabel

Console Output

How Read QR From Image in C#: Figure 3 - QR Code value console output

This code loads the QR code image, reads the first detected QR code, and prints the decoded content. Simple and effective. From here, you can save the QR codes value's for further use.

Handling Multiple QR Codes

If your image contains multiple QR codes (e.g., a sheet of product labels), you can extract all of them. For this example, we'll run the following QR Code image through our program:

How Read QR From Image in C#: Figure 4 - Image with Multiple QR Codes

using IronQr;
using IronSoftware.Drawing;
using System;
class Program
{
    static void Main()
    {
        // Load the image from file
        var inputImage = AnyBitmap.FromFile("SampleCodes.png");
        QrImageInput qrImageInput = new QrImageInput(inputImage);
        // Read the QR code
        QrReader qrReader = new QrReader();
        IEnumerable<QrResult> results = qrReader.Read(qrImageInput);
        // Output the decoded value
        foreach (var result in results)
        {
            Console.WriteLine("QR Code Value: " + result.Value);
        }
    }
}
using IronQr;
using IronSoftware.Drawing;
using System;
class Program
{
    static void Main()
    {
        // Load the image from file
        var inputImage = AnyBitmap.FromFile("SampleCodes.png");
        QrImageInput qrImageInput = new QrImageInput(inputImage);
        // Read the QR code
        QrReader qrReader = new QrReader();
        IEnumerable<QrResult> results = qrReader.Read(qrImageInput);
        // Output the decoded value
        foreach (var result in results)
        {
            Console.WriteLine("QR Code Value: " + result.Value);
        }
    }
}
Imports IronQr
Imports IronSoftware.Drawing
Imports System
Friend Class Program
	Shared Sub Main()
		' Load the image from file
		Dim inputImage = AnyBitmap.FromFile("SampleCodes.png")
		Dim qrImageInput As New QrImageInput(inputImage)
		' Read the QR code
		Dim qrReader As New QrReader()
		Dim results As IEnumerable(Of QrResult) = qrReader.Read(qrImageInput)
		' Output the decoded value
		For Each result In results
			Console.WriteLine("QR Code Value: " & result.Value)
		Next result
	End Sub
End Class
$vbLabelText   $csharpLabel

Output

How Read QR From Image in C#: Figure 5 - QR Code value output

Common Use Cases for QR Code Scanning

Here are a few real-world scenarios where reading QR codes from images becomes valuable:

  • Inventory and Asset Management: Automate item identification by scanning QR codes from package images.
  • Two-Factor Authentication (2FA): Parse QR codes from 2FA setup screens to assist in secure configuration.
  • Mobile App Integration: Launch mobile URLs or app-specific deep links by scanning shared QR screenshots.
  • Event Ticketing: Validate ticket QR codes sent via email or displayed on a screen.
  • Payment Gateways: Extract payment data embedded in QR codes for fintech applications.

In all these use cases, fast and accurate recognition is key—something IronQR handles with ease.

Troubleshooting Tips

If you run into issues reading QR codes, consider the following:

Poor Image Quality

Blurry or low-resolution images can make it difficult to detect a QR code. Use high-quality inputs when possible.

QR Code Not Detected

Make sure the image is not too dark, has strong contrast, and that the QR code is not obscured. Try cropping the image to focus on the QR region.

Exception Handling

Always wrap your QR reading logic in try-catch blocks to gracefully handle corrupted files or unexpected formats:

try
{
    IEnumerable<QrResult> results = qrReader.Read(qrImageInput);
    // Output the decoded value
    foreach (var result in results)
    {
        Console.WriteLine("QR Code Value: " + result.Value);
    }
}
catch (Exception ex)
{
    Console.WriteLine("Error reading QR code: " + ex.Message);
}
try
{
    IEnumerable<QrResult> results = qrReader.Read(qrImageInput);
    // Output the decoded value
    foreach (var result in results)
    {
        Console.WriteLine("QR Code Value: " + result.Value);
    }
}
catch (Exception ex)
{
    Console.WriteLine("Error reading QR code: " + ex.Message);
}
Try
	Dim results As IEnumerable(Of QrResult) = qrReader.Read(qrImageInput)
	' Output the decoded value
	For Each result In results
		Console.WriteLine("QR Code Value: " & result.Value)
	Next result
Catch ex As Exception
	Console.WriteLine("Error reading QR code: " & ex.Message)
End Try
$vbLabelText   $csharpLabel

Final Thoughts

Reading QR codes from images in C# doesn’t have to be difficult. With IronQR, you can integrate QR code scanning into your .NET applications with just a few lines of code. Its simplicity, cross-platform compatibility, and excellent performance make it a go-to tool for developers working on modern, QR-enabled systems.

If you're looking to extend this functionality, consider exploring:

Install the IronQR free trial to get started today, and learn how this library can elevate your QR code tasks.

Preguntas Frecuentes

¿Cómo puedo leer códigos QR de imágenes en C#?

Puede utilizar IronQR para leer códigos QR de imágenes en C#. IronQR ofrece métodos para escanear y extraer datos de códigos QR de varios formatos de imagen como PNG, JPG y TIFF con un código mínimo.

¿Qué pasos se necesitan para configurar IronQR en un proyecto .NET?

Para configurar IronQR en un proyecto .NET, utilice la Consola del Administrador de Paquetes NuGet con el comando Install-Package IronQR, o busque IronQR en la GUI del Administrador de Paquetes NuGet dentro de Visual Studio y haga clic en 'Instalar'.

¿Cómo puede IronQR ayudar con la lectura de códigos QR en imágenes de baja calidad?

IronQR está diseñado para manejar la lectura de códigos QR desde imágenes con calidad variable. Sin embargo, para obtener mejores resultados, asegúrese de que la imagen tenga buen contraste y enfoque en la región del código QR. Si la detección falla, intente mejorar la calidad de la imagen o recortar la imagen.

¿Puede IronQR leer múltiples códigos QR de una sola imagen?

Sí, IronQR puede detectar y leer múltiples códigos QR de una sola imagen. Esto es útil para procesar documentos o etiquetas con múltiples códigos QR.

¿Cuáles son los casos de uso comunes para leer códigos QR en aplicaciones .NET?

Los casos de uso comunes incluyen la gestión de inventario, la autenticación de dos factores, las integraciones de aplicaciones móviles, la venta de entradas para eventos y las pasarelas de pago. IronQR facilita estas aplicaciones al proporcionar capacidades de lectura de códigos QR rápidas y confiables.

¿Cómo asegura IronQR la compatibilidad multiplataforma?

IronQR es compatible con .NET Framework, .NET Core, .NET Standard y .NET 6/7+, brindando compatibilidad multiplataforma para Windows, Linux y otros entornos.

¿Qué debo hacer si IronQR falla al leer un código QR?

Si IronQR falla al leer un código QR, verifique la calidad de la imagen para mayor claridad y contraste. Asegúrese de que no haya obstrucciones en el código QR y considere recortar para enfocar en el área del código QR. Si los problemas persisten, verifique que el formato de archivo sea compatible.

¿Cómo puedo manejar excepciones al usar IronQR para leer códigos QR?

Para manejar excepciones, envuelva su código de IronQR en bloques try-catch. Este enfoque ayuda a gestionar de manera efectiva problemas como archivos corruptos o formatos no compatibles.

¿Cuáles son los beneficios de usar IronQR para el procesamiento de códigos QR?

IronQR ofrece un rendimiento de alta velocidad, soporta múltiples formatos de imagen y proporciona estabilidad a nivel empresarial. Es fácil de integrar en varias aplicaciones .NET, lo que lo hace ideal para desarrolladores que buscan soluciones eficientes para el procesamiento de códigos QR.

¿Cómo puedo mejorar la precisión de detección de códigos QR con IronQR?

Mejore la precisión de detección utilizando imágenes de alta calidad con buen contraste y enfoque. Asegúrese de que los códigos QR no estén oscurecidos y considere usar técnicas de preprocesamiento de imágenes si es necesario.

Jordi Bardia
Ingeniero de Software
Jordi es más competente en Python, C# y C++. Cuando no está aprovechando sus habilidades en Iron Software, está programando juegos. Compartiendo responsabilidades para pruebas de productos, desarrollo de productos e investigación, Jordi agrega un valor inmenso a la mejora continua del producto. La experiencia variada lo mantiene ...
Leer más