Cómo usar seguimiento de OcrProgress en C#

How to Customize and Style Barcodes

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

Over the years, barcode usage has been increasingly popular and is used in a wide range of applications, be it to store data, ID, or URL of a webpage. In some applications, barcodes are made visible on products, resulting in an increased demand for options to style barcodes. Therefore, some barcode types/encodings have come up with their unique appearance such as PDF417, Aztec, IntelligentMail, MaxiCode, DataMatrix, and many more.

In addition to that, IronBarcode provides users with options to further style the barcodes, including aspects like barcode colors, barcode resize, and background colors. This is made possible with the assistance of our open-source library, IronDrawing.

Quickstart: Customize Barcode Color & Background

Here’s a simple example showing how developers can quickly apply custom colors to a barcode’s bars and background using IronBarcode. You’ll see how easy it is to generate a styled barcode with just one chained call.

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("HELLO123", IronBarCode.BarcodeEncoding.Code128)
        .ChangeBarCodeColor(IronSoftware.Drawing.Color.Blue)
        .ChangeBackgroundColor(IronSoftware.Drawing.Color.White)
        .SaveAsImage("styled.png");
  3. Deploy to test on your live environment

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

Resize Barcode Example

Use ResizeTo Method

Resizing a barcode is one aspect of customization that users can achieve with IronBarcode. To use this feature, simply call the ResizeTo method and input the new width and height measurements in pixels (px) for the barcode. This action will trigger a lossless re-rendering of the barcode.

Por favor notaValues that are too small for the barcode to be readable will be ignored.

using IronBarCode;

public class BarcodeResizer
{
    public static void ResizeBarcode(string barcodeText, int newWidth, int newHeight)
    {
        // Generate a barcode
        BarcodeWriter.CreateBarcode(barcodeText, BarcodeEncoding.Code128)
                     // Resize the barcode
                     .ResizeTo(newWidth, newHeight)
                     // Save the resized barcode
                     .SaveAsImage("resized_barcode.png");
    }
}
using IronBarCode;

public class BarcodeResizer
{
    public static void ResizeBarcode(string barcodeText, int newWidth, int newHeight)
    {
        // Generate a barcode
        BarcodeWriter.CreateBarcode(barcodeText, BarcodeEncoding.Code128)
                     // Resize the barcode
                     .ResizeTo(newWidth, newHeight)
                     // Save the resized barcode
                     .SaveAsImage("resized_barcode.png");
    }
}
Imports IronBarCode

Public Class BarcodeResizer
	Public Shared Sub ResizeBarcode(ByVal barcodeText As String, ByVal newWidth As Integer, ByVal newHeight As Integer)
		' Generate a barcode
		BarcodeWriter.CreateBarcode(barcodeText, BarcodeEncoding.Code128).ResizeTo(newWidth, newHeight).SaveAsImage("resized_barcode.png")
	End Sub
End Class
$vbLabelText   $csharpLabel

The ResizeTo method can be invoked on the GeneratedBarcode object. Below are the barcode images generated by running the code snippet above.

Barcode before resize
Barcode after resize

Use ResizeToMil Method

Another aspect of resizing available in IronBarcode is the ResizeToMil method. Unlike the ResizeTo method, this one adjusts the following components:

  • Barcode element: The width of the narrowest barcode element, measured in thousandths of an inch (mil).
  • Height: The height of the barcode, measured in inches (the default is 1 inch).
  • Resolution: Dots per inch (the default is 96 DPI).

This method is particularly suitable for 1D barcodes.

using IronBarCode;

public class BarcodeResizer
{
    public static void ResizeBarcodeToMil(string barcodeText, int elementWidthMil, int heightInches, int dpi = 96)
    {
        // Generate a barcode
        BarcodeWriter.CreateBarcode(barcodeText, BarcodeEncoding.Code128)
                     // Resize the barcode to mil
                     .ResizeToMil(elementWidthMil, heightInches, dpi)
                     // Save the resized barcode
                     .SaveAsImage("resized_barcode_mil.png");
    }
}
using IronBarCode;

public class BarcodeResizer
{
    public static void ResizeBarcodeToMil(string barcodeText, int elementWidthMil, int heightInches, int dpi = 96)
    {
        // Generate a barcode
        BarcodeWriter.CreateBarcode(barcodeText, BarcodeEncoding.Code128)
                     // Resize the barcode to mil
                     .ResizeToMil(elementWidthMil, heightInches, dpi)
                     // Save the resized barcode
                     .SaveAsImage("resized_barcode_mil.png");
    }
}
Imports IronBarCode

Public Class BarcodeResizer
	Public Shared Sub ResizeBarcodeToMil(ByVal barcodeText As String, ByVal elementWidthMil As Integer, ByVal heightInches As Integer, Optional ByVal dpi As Integer = 96)
		' Generate a barcode
		BarcodeWriter.CreateBarcode(barcodeText, BarcodeEncoding.Code128).ResizeToMil(elementWidthMil, heightInches, dpi).SaveAsImage("resized_barcode_mil.png")
	End Sub
End Class
$vbLabelText   $csharpLabel

You can also call this method on the GeneratedBarcode object. In the image below, you'll see the effects of applying the ResizeToMil method: the white spaces at the edges of the barcode are eliminated, and both the narrowest element and the height of the barcode are adjusted according to the parameter values provided to the method.

Barcode before ResizeToMil
Barcode after ResizeToMil

Change Barcode and Background Color

One of the most sought-after features for styling barcodes is the ability to change both the barcode and background colors. Thanks to IronDrawing, IronBarcode provides this capability. By using both the ChangeBarCodeColor and ChangeBackgroundColor methods on the GeneratedBarcode object, users can alter the colors of the barcode and its background. Below is a simple code snippet demonstrating how to achieve this.

using IronBarCode;
using IronSoftware.Drawing; // Required for color manipulation

public class BarcodeColorChanger
{
    public static void ChangeBarcodeColors(string barcodeText, Color barcodeColor, Color backgroundColor)
    {
        // Generate a barcode
        var barcode = BarcodeWriter.CreateBarcode(barcodeText, BarcodeEncoding.Code128);

        // Change the barcode color
        barcode.ChangeBarCodeColor(barcodeColor);

        // Change the background color
        barcode.ChangeBackgroundColor(backgroundColor);

        // Save the colored barcode
        barcode.SaveAsImage("colored_barcode.png");
    }
}
using IronBarCode;
using IronSoftware.Drawing; // Required for color manipulation

public class BarcodeColorChanger
{
    public static void ChangeBarcodeColors(string barcodeText, Color barcodeColor, Color backgroundColor)
    {
        // Generate a barcode
        var barcode = BarcodeWriter.CreateBarcode(barcodeText, BarcodeEncoding.Code128);

        // Change the barcode color
        barcode.ChangeBarCodeColor(barcodeColor);

        // Change the background color
        barcode.ChangeBackgroundColor(backgroundColor);

        // Save the colored barcode
        barcode.SaveAsImage("colored_barcode.png");
    }
}
Imports IronBarCode
Imports IronSoftware.Drawing ' Required for color manipulation

Public Class BarcodeColorChanger
	Public Shared Sub ChangeBarcodeColors(ByVal barcodeText As String, ByVal barcodeColor As Color, ByVal backgroundColor As Color)
		' Generate a barcode
		Dim barcode = BarcodeWriter.CreateBarcode(barcodeText, BarcodeEncoding.Code128)

		' Change the barcode color
		barcode.ChangeBarCodeColor(barcodeColor)

		' Change the background color
		barcode.ChangeBackgroundColor(backgroundColor)

		' Save the colored barcode
		barcode.SaveAsImage("colored_barcode.png")
	End Sub
End Class
$vbLabelText   $csharpLabel
Barcode with color

Add Barcode Annotation Example

IronBarcode also provides the option to add and style barcode annotations. The styling for annotations is also assisted by the functionality from IronDrawing, including editing the annotation color and fonts.

using IronBarCode;
using IronSoftware.Drawing; // Required for font and color manipulation

public class BarcodeAnnotator
{
    public static void AnnotateBarcode(string barcodeText, string annotationText, Font annotationFont, Color annotationColor, float annotationSpacing)
    {
        // Generate a barcode
        var barcode = BarcodeWriter.CreateBarcode(barcodeText, BarcodeEncoding.Code128);

        // Add annotation above the barcode
        barcode.AddAnnotationTextAboveBarcode(annotationText, annotationFont, annotationColor, annotationSpacing);

        // Add barcode value text below the barcode
        barcode.AddBarcodeValueTextBelowBarcode(annotationFont, annotationColor, annotationSpacing);

        // Save the annotated barcode
        barcode.SaveAsImage("annotated_barcode.png");
    }
}
using IronBarCode;
using IronSoftware.Drawing; // Required for font and color manipulation

public class BarcodeAnnotator
{
    public static void AnnotateBarcode(string barcodeText, string annotationText, Font annotationFont, Color annotationColor, float annotationSpacing)
    {
        // Generate a barcode
        var barcode = BarcodeWriter.CreateBarcode(barcodeText, BarcodeEncoding.Code128);

        // Add annotation above the barcode
        barcode.AddAnnotationTextAboveBarcode(annotationText, annotationFont, annotationColor, annotationSpacing);

        // Add barcode value text below the barcode
        barcode.AddBarcodeValueTextBelowBarcode(annotationFont, annotationColor, annotationSpacing);

        // Save the annotated barcode
        barcode.SaveAsImage("annotated_barcode.png");
    }
}
Imports IronBarCode
Imports IronSoftware.Drawing ' Required for font and color manipulation

Public Class BarcodeAnnotator
	Public Shared Sub AnnotateBarcode(ByVal barcodeText As String, ByVal annotationText As String, ByVal annotationFont As Font, ByVal annotationColor As Color, ByVal annotationSpacing As Single)
		' Generate a barcode
		Dim barcode = BarcodeWriter.CreateBarcode(barcodeText, BarcodeEncoding.Code128)

		' Add annotation above the barcode
		barcode.AddAnnotationTextAboveBarcode(annotationText, annotationFont, annotationColor, annotationSpacing)

		' Add barcode value text below the barcode
		barcode.AddBarcodeValueTextBelowBarcode(annotationFont, annotationColor, annotationSpacing)

		' Save the annotated barcode
		barcode.SaveAsImage("annotated_barcode.png")
	End Sub
End Class
$vbLabelText   $csharpLabel
Colored barcode with annotations

As an extension of the previous code snippet, we instantiate two new IronSoftware.Drawing.Font objects to serve as fonts for annotations both above and below the barcode. Only the Font Family is required to instantiate the font.

  • AddAnnotationTextAboveBarcode: Adds custom annotation text above the barcode.
  • AddBarcodeValueTextBelowBarcode: Adds the barcode value below the barcode.

These two methods accept the same parameters: the IronSoftware.Drawing.Font objects, an IronSoftware.Drawing.Color object, and the amount of spacing between the barcode and the text. Additionally, the AddAnnotationTextAboveBarcode method requires a string for the annotation text, as it adds custom text above the barcode.

IronBarcode offers a wide range of opportunities for users to customize and style their barcodes, limited only by one's imagination. To learn more about customizing QR codes, refer to "How to Customize and Add Logos to QR Codes".

Preguntas Frecuentes

¿Cómo puedo cambiar el color de un código de barras en .NET C#?

Puede cambiar el color de un código de barras en .NET C# usando el método ChangeBarCodeColor de IronBarcode. Esto le permite personalizar la apariencia del código de barras para que coincida con sus necesidades de diseño.

¿Qué métodos están disponibles para redimensionar códigos de barras en .NET C#?

IronBarcode proporciona métodos como ResizeTo para redimensionar códigos de barras en píxeles y ResizeToMil para ajustar anchos en milésimas de pulgada, adecuado para códigos de barras 1D.

¿Puedo agregar anotaciones de texto a los códigos de barras en C#?

Sí, puede agregar anotaciones de texto a los códigos de barras en C# usando los métodos AddAnnotationTextAboveBarcode y AddBarcodeValueTextBelowBarcode de IronBarcode, permitiendo un etiquetado e información mejorados.

¿Qué debo hacer si mi código de barras redimensionado es ilegible?

Si su código de barras redimensionado se vuelve ilegible debido a dimensiones pequeñas, IronBarcode ignorará esos valores para mantener la legibilidad, asegurando que el código de barras siga siendo funcional.

¿Cómo aseguro un renderizado de alta calidad de código de barras en .NET C#?

El renderizado de alta calidad de un código de barras se logra usando los métodos de redimensionamiento sin pérdida de IronBarcode como ResizeTo y ResizeToMil, que mantienen la calidad de la imagen al ajustar el tamaño.

¿Qué biblioteca puede ayudar con el color y el estilo de anotaciones de códigos de barras?

IronDrawing, una biblioteca de código abierto, ayuda con la manipulación de colores y el estilo de anotaciones, permitiendo diseños de código de barras creativos y personalizados en IronBarcode.

¿Es posible cambiar la fuente de las anotaciones de códigos de barras en C#?

Sí, puede personalizar la fuente de las anotaciones de códigos de barras usando objetos IronSoftware.Drawing.Font, proporcionando flexibilidad en el estilo de texto por encima y por debajo del código de barras.

¿Dónde puedo descargar la biblioteca para personalización de códigos de barras en C#?

La biblioteca de C# para personalización de códigos de barras se puede descargar desde NuGet en https://www.nuget.org/packages/BarCode/, permitiéndole comenzar a personalizar códigos de barras con IronBarcode.

¿Cómo puedo personalizar el color de fondo de un código de barras en .NET C#?

Puede personalizar el color de fondo de un código de barras en .NET C# usando el método ChangeBackgroundColor de IronBarcode, permitiendo oportunidades de diseño y marca únicas.

¿Cuál es la mejor manera de mantener la legibilidad del código de barras después de redimensionarlo?

Para mantener la legibilidad después de redimensionar, use los métodos de redimensionamiento de IronBarcode que aseguran que las dimensiones del código de barras no comprometan su funcionalidad y claridad.

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