Cómo Crear Imágenes de Código de Barras y Código QR en C#

How to Create Barcode Images

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

Quickstart: Create and Save a Code128 Barcode in One Line

Use IronBarcode’s one-line API to create a Code128 barcode from a string and save it as a PNG image. Developers can get started immediately—no fuss, no boilerplate—just supply the data, choose the encoding and size, and write your image file.

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.

    IronBarCode.BarcodeWriter.CreateBarcode("Sample123", BarcodeEncoding.Code128, 250, 100).SaveAsPng("Barcode.png");
  3. Deploy to test on your live environment

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

Generate Barcodes and Save as Image Files

Besides reading barcodes, IronBarcode is a powerful tool that also allows users to write barcodes with very minimal coding. To achieve this, simply call the CreateBarcode() method from the BarcodeWriter class, where the barcode value, type, width, and height can be specified in the method parameters. This outputs a GeneratedBarcode object, which can then be saved as an image file using the SaveAs() method. Let's discuss each parameter in detail and later see how to implement barcode writing with a code snippet.

Barcode Value

The BarcodeWriter.CreateBarcode() method accepts multiple data types for barcode values. These include byte[] array, MemoryStream, and string. The lengths of the string and what characters are accepted vary depending on the barcode type, but this is all detailed within our documentation.

Barcode Encoding Types

IronBarcode supports a wide variety of barcode formats for writing—the complete list can be found in our Supported Barcode Formats article. These barcode types all have their own unique properties, specialties, and uses—you can research which one is the best fit for your use case with our documentation.

Width and Height

Set the width and height of the output barcode image in pixels. By default, both measurements are set at 250 px. Several barcode types, such as QR and PDF417, require having certain dimensions to be compliant, so for input widths and heights that don't match the required dimensions of the barcode, the barcode will be generated at the compliant dimensions and whitespace will fill the remaining space. If the dimensions are too small for the barcode, an exception will be thrown.

Import Barcodes as Image

When creating a barcode with the BarcodeWriter.CreateBarcode() method, a GeneratedBarcode object will be generated. With this object, we can save the barcode to a variety of image types with several SaveAs() methods specific to each image format. These methods include:

  • SaveAsGif(): This method saves the GeneratedBarcode as a GIF image file and accepts the image file path as a string argument.
  • SaveAsJpeg(): This method saves the GeneratedBarcode as a JPEG image file and accepts the image file path as a string argument.
  • SaveAsPng(): This method saves the GeneratedBarcode as a PNG image file and accepts the image file path as a string argument.
  • SaveAsTiff(): This method saves the GeneratedBarcode as a TIFF image file and accepts the image file path as a string argument.
  • SaveAsWindowsBitmap(): This method saves the GeneratedBarcode as a BMP image file and accepts the image file path as a string argument.
  • SaveAsImage(): This is a general method for saving the GeneratedBarcode as an image file—users must specify the desired file format extension when inputting the file path.

Generate a Barcode and Save As Image File

Now we will use BarcodeWriter.CreateBarcode() to demonstrate the creation of a Code128 barcode, and save it to disk as a JPEG image file.

:path=/static-assets/barcode/content-code-examples/how-to/create-barcode-images-one-dimensional.cs
using IronBarCode;

BarcodeWriter.CreateBarcode("IronBarcode123", BarcodeEncoding.Code128, 200, 100).SaveAsJpeg("OneDBarcode.jpeg");
Imports IronBarCode

BarcodeWriter.CreateBarcode("IronBarcode123", BarcodeEncoding.Code128, 200, 100).SaveAsJpeg("OneDBarcode.jpeg")
$vbLabelText   $csharpLabel
One dimensional barcode from snippet

Generate QR Codes and Save as Image Files

One of the most popular barcodes nowadays, QR code, which is also one of the barcodes classified as a two-dimensional barcode, is fully supported by IronBarcode. Due to its versatility, cosmetic appeal, and highly customizable features, QR codes have gained high popularity among users.

Different from the creation of 1-dimensional and other barcodes, creating QR codes will be using a different method from a different class in IronBarcode because of the intricacy of QR codes which require different properties and arguments to produce high-quality QR codes as required by customers. To create QR codes in IronBarcode, users will need to call the CreateQrCode() method from the QRCodeWriter class. QRCodeWriter.CreateQrCode() accepts 4 arguments: the barcode value as the first argument, size of the output QR code as the second, QRCodeWriter.QrErrorCorrectionLevel enum field as the third argument, and lastly the QRVersion. Let us discuss the arguments for this method in detail.

QR Code Values

Similar to the BarcodeWriter.CreateBarcode() method, QRCodeWriter.CreateQrCode() first accepts a value for the QR Code which can be numerical, alphabetical, or alphanumerical. These values can be input inside the method as byte[] array, MemoryStream, and System.String type.

QR Code Size

Users can also specify the size of the QR code directly into the method as Int32 type. The measurement unit for QR code size used in this method is in pixels (px). The default QR code size is 500 px.

QR Error Correction Level

QRErrorCorrectionLevel is a member property of the QRCodeWriter class where it has 4 fields: Highest, High, Medium, and Low. Basically, this property is the fault tolerance level of a QR code, where a higher correction level creates more complex QR codes that are less prone to reading errors, even if it is damaged, or partially obscured. Now, let us discuss in detail each of the fields in this property, as well as look at the difference in the appearance of the QR code produced.

QRErrorCorrectionLevel.Highest

QR codes generated with the Highest correction level will have the most complex QR code image, with 30% of it being error correction. The QR code produced can also be stamped with a logo or image graphics on the QR code.

QR Code with highest correction level

QRErrorCorrectionLevel.High

Setting the property field to be High will result in the application of 25% error correction in the QR code image. It will be less complex than the QR code image produced from QRErrorCorrectionLevel.Highest.

QR Code with high correction level

QRErrorCorrectionLevel.Medium

This field applies only 15% error correction in the QR code image. By using this setting, users will get to produce QR codes faster; however, they are more prone to errors.

QR Code with medium correction level

QRErrorCorrectionLevel.Low

This is the lowest setting for error correction level, which only applies 7% error correction in the QR code image, resulting in the least complex QR Code.

QR Code with low correction level

QR Version

QR Version is the symbol version of a QR code that ranges from 1 to 40. A higher QR version will produce a more complex QR code, enabling users to store more data, and vice versa for the lower version of QR code. Please note, however, if the QR version is set too low, issues might occur when users are trying to encode more data than what is allowed by the version. Setting the QR version as 0 will automatically assign the appropriate QR version based on the value to be encoded. Please refer to this site for more information on QR version: QR Version

Create a QR Code Image

The code snippet below demonstrates how to use the QRCodeWriter.CreateQrCode() method in IronBarcode to write a QR code and save it as an image file to disk by using the SaveAsJpeg() method.

:path=/static-assets/barcode/content-code-examples/how-to/create-barcode-images-qr.cs
using IronBarCode;

QRCodeWriter.CreateQrCode("IronBarcode1234", 250, QRCodeWriter.QrErrorCorrectionLevel.Medium, qrVersion: 0).SaveAsJpeg("QRMedium.jpeg");
Imports IronBarCode

QRCodeWriter.CreateQrCode("IronBarcode1234", 250, QRCodeWriter.QrErrorCorrectionLevel.Medium, qrVersion:= 0).SaveAsJpeg("QRMedium.jpeg")
$vbLabelText   $csharpLabel
QR Code with medium correction level

From the code snippet above, an alphanumerical value was used as the value to be encoded in the QR code, and we used 250 pixels as the measurement of the produced QR code. We also specified the error correction of the produced QR code to be medium and let the program decide which QR code version is suitable for our QR code value. Apart from that, we also used SaveAsJpeg() that accepts the QR code image file name with the image format extension, which is a JPEG in this case, to be saved as the argument.

Preguntas Frecuentes

¿Cómo creo una imagen de código de barras en .NET?

Para crear una imagen de código de barras en .NET, utiliza la biblioteca IronBarcode. Primero, descárgala de NuGet, luego utiliza el método BarcodeWriter.CreateBarcode(), especificando el valor, tipo, ancho y alto del código de barras. Guarda la imagen resultante del código de barras usando métodos como SaveAsPng() o SaveAsJpeg().

¿Qué formatos de código de barras son compatibles en .NET?

La biblioteca .NET Barcode Library admite varios formatos de código de barras, incluyendo Code128 y códigos QR. Para obtener una lista completa de los formatos soportados, consulta la documentación de IronBarcode.

¿Cómo puedo guardar un código de barras como una imagen JPEG?

Puedes guardar un código de barras como una imagen JPEG utilizando el método SaveAsJpeg() después de generar el código de barras con el método BarcodeWriter.CreateBarcode() de IronBarcode.

¿Qué debo hacer si las dimensiones de mi código de barras son incorrectas?

Si las dimensiones especificadas de tu código de barras son incorrectas, IronBarcode puede ajustar el tamaño para mantener la conformidad o lanzar una excepción. Asegúrate de proporcionar dimensiones adecuadas para tu tipo de código de barras.

¿Cómo genero un código QR en C#?

Para generar un código QR en C#, utiliza el método QRCodeWriter.CreateQrCode() de IronBarcode. Proporciona el valor del código, tamaño, nivel de corrección de errores y versión del QR. Guarda el código QR usando métodos como SaveAsPng().

¿Qué factores afectan el nivel de corrección de errores de un código QR?

El nivel de corrección de errores de un código QR afecta su tolerancia a fallos y complejidad. IronBarcode ofrece cuatro niveles: Máximo, Alto, Medio y Bajo, cada uno influenciando la cantidad de datos que se puede recuperar si el código QR está dañado.

¿Puedo usar distintos tipos de datos para códigos de barras en .NET?

Sí, IronBarcode admite varios tipos de datos para los valores de los códigos de barras, incluyendo cadenas de texto, arreglos de bytes y MemoryStreams, permitiendo formatos de entrada flexibles para la creación de códigos de barras.

¿Cómo influye la versión del QR en la capacidad de datos de un código QR?

La versión del QR en IronBarcode determina la capacidad de datos y la complejidad del código QR. Las versiones varían de 1 a 40, permitiendo un mayor almacenamiento de datos en las versiones más altas.

¿Qué espacio de nombres debo incluir para usar IronBarcode?

Incluye el espacio de nombres IronBarcode en tu proyecto C# para acceder a todas las funcionalidades de creación y manipulación de códigos de barras proporcionadas por la biblioteca.

Hairil Hasyimi Bin Omar
Ingeniero de Software
Como todos los grandes ingenieros, Hairil es un ávido aprendiz. Está refinando su conocimiento de C#, Python y Java, usando ese conocimiento para agregar valor a los miembros del equipo en Iron Software. Hairil se unió al equipo de Iron Software desde la Universiti Teknologi MARA en Malasia, donde se ...
Leer más
¿Listo para empezar?
Nuget Descargas 1,935,276 | Versión: 2025.11 recién lanzado