Saltar al pie de página
USO DE IRONBARCODE

Cómo Hacer un Código QR para un Enlace (Tutorial de C#)

1.0 Introduction

The Quick Response Code, or QR code, has its roots in the Japanese car sector. It is also known as the QR Symbol, QR Graphic, or QR Code Graphic. Masahiro Hara created it in 1994, and its initial application was as a quick and easy tool to monitor the progress of vehicles as they were being assembled in factories. Since then, the use of QR codes as a barcode substitute has grown significantly outside the car manufacturing industry. Its greater reading speed and storage capacity are to blame for this. QR codes can be used to exchange and store information for marketing purposes and for social media sites and accounts in addition to tracking and identifying products. The static QR code which is generated from the application can be scanned with the camera application.

2.0 IronBarcode Features

With IronBarcode's QR Code Library, creating dynamic QR codes is simple. With just a few lines of code, this straightforward library can quickly create a QR code. IronBarcode can generate QR codes with high quality, and it makes it easy for the QR Code scanner to read custom codes.

  • The majority of barcode formats and QR standards, including UPC A/E, EAN 8/13, Code 39/93/128, ITF, MSI, RSS 14/Expanded, Databar, and CodaB, may be read and written by IronBarcode.
  • IronBarcode can read scans and live video frames, correcting rotation, noise, distortion, and skewing. IronBarcode automatically preprocesses barcode images to increase reading efficiency and accuracy while creating QR codes. They allow for content editing, dynamic QR code are particularly popular.
  • IronBarcode can run on a number of cores and threads (particularly helpful for batch processing servers).
  • IronBarcode can automatically locate one or more barcodes in single- and multipage documents.
  • IronBarcode works with both the .NET Framework and .NET Core implementations, and it supports 32- and 64-bit architectures.
  • On PC and mobile platforms, IronBarcode supports console, desktop, cloud, and web apps.
  • PDF, JPG, TIFF, GIF, BMP, PNG, and HTML are just a few of the file and stream formats that IronBarcode can produce QR code pictures for.

3.0 Creating QR Code Image

3.1 Using IronBarcode from Windows/Console Application

The proceeding sections of this article present an example to demonstrate how easily our library generates QR codes.

Step 1. Creating a New Project for Creating QR Codes

Open Visual Studio and click the File menu option for New Project.

Click Next after selecting the Console App template in the ensuing box.

How to Make A QR Code For A Link (C# Tutorial): Figure 1

Enter any project name you choose (for instance, QR Code Generator) in the Project name text area, and then enter the location of the new project in the Location field. Click the Next button to proceed after that.

How to Make A QR Code For A Link (C# Tutorial): Figure 2

Select a Dot NET Framework (here, we're using Dot NET 6.0 (Long term support)) from the Framework drop-down option, then click Create.

How to Make A QR Code For A Link (C# Tutorial): Figure 3

Step 2. Install the IronBarcode library

Download the necessary IronBarcode library by entering the code below into the package manager console:

Install-Package BarCode

How to Make A QR Code For A Link (C# Tutorial): Figure 4

Alternatively, we can conduct a search using the NuGet package management and download the "IronBarcode" package, which will list all results and allow us to choose the one we need to download.

How to Make A QR Code For A Link (C# Tutorial): Figure 5

Step 3. Generate a QR Code Image

IronBarcode allows us to create a QR code with a few lines of code. Use the QRCodeWriter.CreateQrCode method to create a new QR code as shown in the following code:

using IronBarCode;

// Create a QR code with a specified URL and dimensions,
// and save it as a PNG file.
QRCodeWriter.CreateQrCode("www.google.com", 500, QRCodeWriter.QrErrorCorrectionLevel.Medium, 0).SaveAsPng("NewQR.png");
using IronBarCode;

// Create a QR code with a specified URL and dimensions,
// and save it as a PNG file.
QRCodeWriter.CreateQrCode("www.google.com", 500, QRCodeWriter.QrErrorCorrectionLevel.Medium, 0).SaveAsPng("NewQR.png");
Imports IronBarCode

' Create a QR code with a specified URL and dimensions,
' and save it as a PNG file.
QRCodeWriter.CreateQrCode("www.google.com", 500, QRCodeWriter.QrErrorCorrectionLevel.Medium, 0).SaveAsPng("NewQR.png")
$vbLabelText   $csharpLabel

The data to be encoded in the code image (which might be a URL or a Stream) is the only mandatory parameter for the CreateQrCode method. Additionally, the method takes three optional parameters:

  • The graphic's default dimensions are 500 pixels wide by 500 pixels high.
  • An error correction level. Low, Medium, High, and Highest are the four levels of error correction offered by IronBarcode. The CreateQrCode method by default uses the highest level of correction (QRCodeWriter.QrErrorCorrectionLevel.Highest).
  • The version number of the QR code. For a list of acceptable variations, visit this page. The method is told to use the right version number based on the data it will encode if the value is 0 (the default value).

The sample above uses the medium level of error correction to produce a 500 by 500 pixel graphic that creates a custom QR code. Next, we can save the generated QR codes as a PNG file at a specified file location by calling the SaveAsPng method.

How to Make A QR Code For A Link (C# Tutorial): Figure 6

We'll then look at an example of a use-case where a user or business wants to add a company logo to a generated QR code. To accomplish this, the QrCodeWriter.CreateQrCodeWithLogo method is used in the example code below.

using System.Drawing; // Necessary for Color type

// Create a QR code with a logo included.
var QRWithLogo = QRCodeWriter.CreateQrCodeWithLogo("www.google.com", "qrWithlogo.png", 500);

// Customize the color of the QR code using the ChangeBarCodeColor method.
QRWithLogo.ChangeBarCodeColor(Color.DarkRed);

// Save the customized QR code as a new PNG file.
QRWithLogo.SaveAsPng("NewQR_Code.png");
using System.Drawing; // Necessary for Color type

// Create a QR code with a logo included.
var QRWithLogo = QRCodeWriter.CreateQrCodeWithLogo("www.google.com", "qrWithlogo.png", 500);

// Customize the color of the QR code using the ChangeBarCodeColor method.
QRWithLogo.ChangeBarCodeColor(Color.DarkRed);

// Save the customized QR code as a new PNG file.
QRWithLogo.SaveAsPng("NewQR_Code.png");
Imports System.Drawing ' Necessary for Color type

' Create a QR code with a logo included.
Private QRWithLogo = QRCodeWriter.CreateQrCodeWithLogo("www.google.com", "qrWithlogo.png", 500)

' Customize the color of the QR code using the ChangeBarCodeColor method.
QRWithLogo.ChangeBarCodeColor(Color.DarkRed)

' Save the customized QR code as a new PNG file.
QRWithLogo.SaveAsPng("NewQR_Code.png")
$vbLabelText   $csharpLabel

In the above example, we encoded the string value of the URL "www.google.com" into a new QR code that embeds an image from that website into a given file location.

Graphics are included in the QR code above. The logo is automatically positioned to that size and sized to match the QR code square grid so that the pure code can still be read. We can also customize the color of the QR address bar code using the ChangeBarCodeColor method, which offers a range of code colors we can use on the QR code. One uses Color-class-types, while the other makes use of HTML hex color notation as follows:

QRWithLogo.ChangeBarCodeColor(System.Drawing.ColorTranslator.FromHtml("#8B0000"));
QRWithLogo.ChangeBarCodeColor(System.Drawing.ColorTranslator.FromHtml("#8B0000"));
QRWithLogo.ChangeBarCodeColor(System.Drawing.ColorTranslator.FromHtml("#8B0000"))
$vbLabelText   $csharpLabel

The above line of code specifies the dark red color of the barcode. Then, as the code instructs, we save it as a PNG file. We can also save QR codes in other file formats such as HTML:

QRWithLogo.SaveAsHtmlFile("test.html");
QRWithLogo.SaveAsHtmlFile("test.html");
QRWithLogo.SaveAsHtmlFile("test.html")
$vbLabelText   $csharpLabel

The outcome of the source code above is displayed in the image below.

How to Make A QR Code For A Link (C# Tutorial): Figure 7

QR codes can be saved in other file formats such as HTML:

QRWithLogo.SaveAsHtmlFile("test.html");
QRWithLogo.SaveAsHtmlFile("test.html");
QRWithLogo.SaveAsHtmlFile("test.html")
$vbLabelText   $csharpLabel

How to Make A QR Code For A Link (C# Tutorial): Figure 8

Using IronBarcode QR Code generator website

IronBarcode can be used in web applications as well. The MVC Dot Net core 6.0 sample code is provided below.

public IActionResult Index()
{
    // Generate a QR code for www.google.com
    var barcode = QRCodeWriter.CreateQrCode("www.google.com", 500, QRCodeWriter.QrErrorCorrectionLevel.Medium, 0);

    // Save the QR code as a PNG file
    barcode.SaveAsPng("Barcode.png");

    // Get the file path to the saved QR code
    var filePath = Path.Combine(Directory.GetCurrentDirectory(), "Barcode.png");

    // Return the file as a physical file result to be downloaded
    return PhysicalFile(filePath, "image/png", "Barcode.png");
}
public IActionResult Index()
{
    // Generate a QR code for www.google.com
    var barcode = QRCodeWriter.CreateQrCode("www.google.com", 500, QRCodeWriter.QrErrorCorrectionLevel.Medium, 0);

    // Save the QR code as a PNG file
    barcode.SaveAsPng("Barcode.png");

    // Get the file path to the saved QR code
    var filePath = Path.Combine(Directory.GetCurrentDirectory(), "Barcode.png");

    // Return the file as a physical file result to be downloaded
    return PhysicalFile(filePath, "image/png", "Barcode.png");
}
Public Function Index() As IActionResult
	' Generate a QR code for www.google.com
	Dim barcode = QRCodeWriter.CreateQrCode("www.google.com", 500, QRCodeWriter.QrErrorCorrectionLevel.Medium, 0)

	' Save the QR code as a PNG file
	barcode.SaveAsPng("Barcode.png")

	' Get the file path to the saved QR code
	Dim filePath = Path.Combine(Directory.GetCurrentDirectory(), "Barcode.png")

	' Return the file as a physical file result to be downloaded
	Return PhysicalFile(filePath, "image/png", "Barcode.png")
End Function
$vbLabelText   $csharpLabel

The code that we used for the Windows/console program is the same as the one that is provided above. The above code first generates a QR code file before returning it. Then QR code can be downloaded by the user as a PNG file. We can also make it available for use on mobile devices and online forms.

How to Make A QR Code For A Link (C# Tutorial): Figure 9

How to Make A QR Code For A Link (C# Tutorial): Figure 10

For more code tutorials for IronBarcode click here.

4.0 Conclusion

One of the most effective libraries for creating and identifying barcodes is IronBarcode. Additionally, it is among the quickest libraries for creating and reading barcodes. Different operating systems are compatible with the library.

It is simple to develop and supports a wide range of barcode formats. We can alter the color, line width, height, barcode text, and more.

You may find the licensing information here. Both a free QR code generator library for developer license and a premium edition of IronBarcode are available. It includes free support and updates for a year.

Users can also benefit from Iron Suite, a Suite of 5 professional ASP.NET core libraries including IronBarcode, IronXL, IronPDF, and more.

Preguntas Frecuentes

¿Cuál es la importancia de los códigos QR en las aplicaciones modernas?

Los códigos QR proporcionan una forma rápida y eficiente de almacenar e intercambiar información, lo que los hace esenciales en muchas aplicaciones modernas como marketing, seguimiento de productos y sistemas de pago. IronBarcode facilita la generación y personalización de códigos QR para estas aplicaciones.

¿Cómo puedo crear un código QR para un enlace web en C#?

Puedes crear un código QR para un enlace web usando IronBarcode llamando al método QRCodeWriter.CreateQrCode con la URL como parámetro. Personaliza la apariencia del código QR y guárdalo en formatos como PNG o PDF.

¿Cuáles son las ventajas de usar IronBarcode para la generación de códigos QR?

IronBarcode ofrece generación de códigos QR de alta calidad con características personalizables como cambios de color y la inserción de logotipos. Admite varios formatos de código de barras y salidas de archivo, lo que lo hace versátil para diferentes aplicaciones.

¿Cómo integro la generación de códigos QR en una aplicación web .NET?

Para integrar la generación de códigos QR en una aplicación web .NET, usa IronBarcode con MVC Dot Net core 6.0. La biblioteca te permite generar códigos QR dinámicamente dentro de tu aplicación web y soporta varios formatos de descarga.

¿Puedo personalizar las dimensiones del código QR y los niveles de corrección de errores usando la biblioteca?

Sí, IronBarcode te permite personalizar tanto las dimensiones como los niveles de corrección de errores de los códigos QR. Usa el método CreateQrCode con parámetros específicos para ajustar estas características según tus necesidades.

¿Cómo agrego un logo a un código QR usando C#?

Para agregar un logo a un código QR en C#, usa el método QRCodeWriter.CreateQrCodeWithLogo de IronBarcode. Esta característica te permite insertar un logo dentro del código QR, mejorando la visibilidad de la marca mientras se mantiene la legibilidad del código.

¿Qué consejos de solución de problemas están disponibles para los problemas de generación de códigos QR?

Si encuentras problemas con la generación de códigos QR, asegúrate de que la biblioteca esté correctamente instalada a través de NuGet y que todos los métodos se usen como se documenta. Verifica cualquier problema de compatibilidad con la configuración de tu proyecto o la versión de .NET.

¿Qué formatos de archivo son compatibles para guardar los códigos QR generados con la biblioteca?

IronBarcode admite guardar códigos QR en una variedad de formatos de archivo, incluidos PDF, JPG, TIFF, GIF, BMP, PNG y HTML, proporcionando flexibilidad para diferentes casos de uso.

¿Hay una versión gratuita disponible para la biblioteca de generación de códigos QR?

Sí, IronBarcode ofrece una versión gratuita de su biblioteca de generación de códigos QR para desarrolladores. También hay una versión premium que incluye funciones adicionales, soporte y actualizaciones.

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