Przejdź do treści stopki
KORZYSTANIE Z IRONBARCODE

Jak generować kod kreskowy Code 128 w C#

Barcodes are crucial in modern business operations, from inventory management to product labeling and shipping. Code 128 stands out as a versatile and widely used option among the various barcode code sets. In this article, we'll explore how to build a Code 128 barcode generator in C# using the IronBarcode library.

How to Generate Code 128 Barcode in C

  1. Install the IronBarcode library
  2. Generate a barcode using Code 128 Encoding
  3. Zmiana rozmiaru BarCode
  4. Style the barcode by changing the background and barcode color
  5. Read the created barcode

Introduction to Code 128 Barcodes

Code 128 code set is a high-density, variable-length linear barcode that can encode both alphanumeric data and special characters. It's self-checking, which includes a checksum digit to ensure data accuracy. The Code 128 encoding scheme supports three control characters:

  1. Character Set A: Includes uppercase letters, digits, and special characters.
  2. Character Set B: Includes uppercase letters, lowercase letters, digits, and additional special characters.
  3. Character Set C: Encodes pairs of digits (00 to 99).

Why IronBarcode?

IronBarcode is a robust .NET library facilitating barcode generation, decoding, and customization. With support for various Barcode Encoding like Code 128, Code 39, Code 93, Code EAN 13, EAN 8, QR codes, and others. It offers an intuitive API for content, size, and appearance adjustments. Its decoding capabilities, automatic checksum calculation, and image export make it a valuable tool for developers in inventory management and beyond. The library's customization options for properties, margins, fonts, and colors enhance its versatility in barcode-related tasks.

Creating Code 128 Barcode Generator in C

Now, we will write code to generate a Code 128 barcode image in C#. The first step is to install the IronBarcode library in our project. The project can be of any type such as Windows Forms, web forms, MAUI, Xamarin, ASP.NET MVC, Razor, or Blazor projects.

Instalacja biblioteki IronBarcode

To install the IronBarcode NuGet package using the Package Manager Console in Visual Studio, you can follow these steps:

  1. Otwórz program Visual Studio.
  2. In the top menu, go to "View" > "Other Windows" > "Package Manager Console" to open the Package Manager Console.
  3. In the Package Manager Console, you can use the Install-Package command to install the IronBarcode package. Wpisz następujące polecenie i naciśnij Enter:

    Install-Package BarCode
    Install-Package BarCode
    SHELL
  4. This command will download and install the latest version of the IronBarcode NuGet package and its dependencies into your project.

Add the following namespace to use the barcode library in your project.

using IronBarCode;
using IronBarCode;
Imports IronBarCode
$vbLabelText   $csharpLabel

Generate Code 128 Barcode Image

The following code will generate a Code 128 barcode.

// Create a barcode from the input string and specify encoding type as Code 128
var myBarcode = BarcodeWriter.CreateBarcode("12345ABC12345", BarcodeWriterEncoding.Code128);

// Save the barcode image as a JPEG file
myBarcode.SaveAsJpeg("myBarcode.Jpeg");
// Create a barcode from the input string and specify encoding type as Code 128
var myBarcode = BarcodeWriter.CreateBarcode("12345ABC12345", BarcodeWriterEncoding.Code128);

// Save the barcode image as a JPEG file
myBarcode.SaveAsJpeg("myBarcode.Jpeg");
' Create a barcode from the input string and specify encoding type as Code 128
Dim myBarcode = BarcodeWriter.CreateBarcode("12345ABC12345", BarcodeWriterEncoding.Code128)

' Save the barcode image as a JPEG file
myBarcode.SaveAsJpeg("myBarcode.Jpeg")
$vbLabelText   $csharpLabel

This code creates a barcode from the input string and saves it as a JPEG image file named "myBarcode.Jpeg." The specific encoding used is Code 128, which can represent alphanumeric characters.

Wyjaśnienie

The first line of code creates a new variable named myBarcode. It uses the BarcodeWriter.CreateBarcode method to generate a barcode based on the input string "12345ABC12345".

The second argument, BarcodeWriterEncoding.Code128, specifies the encoding type for the barcode. In this case, it's using the Code 128 encoding, which is commonly used for alphanumeric data. The resulting barcode is stored in the myBarcode variable.

The second line saves the generated barcode as a JPEG image file. The filename for the saved image is "myBarcode.Jpeg". The format of the saved image is JPEG (Joint Photographic Experts Group).

Wynik

The generated barcode is as:

How to Generate Code 128 barcode in C#: Figure 1 - Outputted barcode from the previous code

This code can now be read using a barcode reading device.

Now, let's resize our barcode.

Resize Barcode

The following code will resize our barcode as per the given dimension.

static void Main(string[] args)
{
    // Create a barcode from the input string and specify encoding type as Code 128
    var myBarcode = BarcodeWriter.CreateBarcode("12345ABC12345", BarcodeWriterEncoding.Code128);

    // Resize the barcode image to the specified width and height (in pixels)
    myBarcode.ResizeTo(800, 300);

    // Save the resized barcode image as a JPEG file
    myBarcode.SaveAsJpeg("myBarcode.Jpeg");
}
static void Main(string[] args)
{
    // Create a barcode from the input string and specify encoding type as Code 128
    var myBarcode = BarcodeWriter.CreateBarcode("12345ABC12345", BarcodeWriterEncoding.Code128);

    // Resize the barcode image to the specified width and height (in pixels)
    myBarcode.ResizeTo(800, 300);

    // Save the resized barcode image as a JPEG file
    myBarcode.SaveAsJpeg("myBarcode.Jpeg");
}
Shared Sub Main(ByVal args() As String)
	' Create a barcode from the input string and specify encoding type as Code 128
	Dim myBarcode = BarcodeWriter.CreateBarcode("12345ABC12345", BarcodeWriterEncoding.Code128)

	' Resize the barcode image to the specified width and height (in pixels)
	myBarcode.ResizeTo(800, 300)

	' Save the resized barcode image as a JPEG file
	myBarcode.SaveAsJpeg("myBarcode.Jpeg")
End Sub
$vbLabelText   $csharpLabel

The code for creating and saving barcodes remains the same. Just add the additional line to resize the barcode.

The ResizeTo() method resizes the barcode image stored in the myBarcode variable. The method ResizeTo is called on the myBarcode object. The two arguments passed to ResizeTo are width and height. In this case, the width is set to 800 pixels and the height is set to 300 pixels.

In this way, we can set the minimum width and bar module height. The resulting barcode image will have these dimensions after resizing as shown below.

Obraz BarCode

How to Generate Code 128 barcode in C#: Figure 2 - Resized barcode from the previous code

Now, let's style our barcode.

Style Code 128 Barcode

Now, let's style our barcode by changing the background color and barcode color.

static void Main(string[] args)
{
    // Create a barcode from the input string and specify encoding type as Code 128
    var myBarcode = BarcodeWriter.CreateBarcode("12345ABC12345", BarcodeWriterEncoding.Code128);

    // Resize the barcode image to the specified width and height (in pixels)
    myBarcode.ResizeTo(800, 300);

    // Change the background color of the barcode
    myBarcode.ChangeBackgroundColor(IronSoftware.Drawing.Color.Cornsilk);

    // Change the barcode color
    myBarcode.ChangeBarCodeColor(IronSoftware.Drawing.Color.Brown);

    // Save the styled barcode image as a JPEG file
    myBarcode.SaveAsJpeg("myBarcode.Jpeg");
}
static void Main(string[] args)
{
    // Create a barcode from the input string and specify encoding type as Code 128
    var myBarcode = BarcodeWriter.CreateBarcode("12345ABC12345", BarcodeWriterEncoding.Code128);

    // Resize the barcode image to the specified width and height (in pixels)
    myBarcode.ResizeTo(800, 300);

    // Change the background color of the barcode
    myBarcode.ChangeBackgroundColor(IronSoftware.Drawing.Color.Cornsilk);

    // Change the barcode color
    myBarcode.ChangeBarCodeColor(IronSoftware.Drawing.Color.Brown);

    // Save the styled barcode image as a JPEG file
    myBarcode.SaveAsJpeg("myBarcode.Jpeg");
}
Shared Sub Main(ByVal args() As String)
	' Create a barcode from the input string and specify encoding type as Code 128
	Dim myBarcode = BarcodeWriter.CreateBarcode("12345ABC12345", BarcodeWriterEncoding.Code128)

	' Resize the barcode image to the specified width and height (in pixels)
	myBarcode.ResizeTo(800, 300)

	' Change the background color of the barcode
	myBarcode.ChangeBackgroundColor(IronSoftware.Drawing.Color.Cornsilk)

	' Change the barcode color
	myBarcode.ChangeBarCodeColor(IronSoftware.Drawing.Color.Brown)

	' Save the styled barcode image as a JPEG file
	myBarcode.SaveAsJpeg("myBarcode.Jpeg")
End Sub
$vbLabelText   $csharpLabel

The code for generating and saving barcodes is the same. I've just added two additional lines for changing the background and barcode color. The explanation is as follows:

  • ChangeBackgroundColor: The method ChangeBackgroundColor is called on the myBarcode object. This method changes the background color of the barcode image. The argument passed to ChangeBackgroundColor is IronSoftware.Drawing.Color.Cornsilk, which specifies the desired background color. In this case, the background color is set to Cornsilk, which is a pale yellowish color.

  • ChangeBarCodeColor: The method ChangeBarCodeColor is called on the myBarcode object. This method changes the color of the barcode bars. The argument passed to ChangeBarCodeColor is IronSoftware.Drawing.Color.Brown, which specifies the desired barcode color. In this case, the barcode color is set to Brown.

Wynik

Our styled barcode is as:

How to Generate Code 128 barcode in C#: Figure 3 - Outputted styled barcode from the previous code

Read Code 128 Barcode

We have learned to generate a Code 128 barcode. Let's write code to read the barcode:

static void Main(string[] args)
{
    // Read barcodes from the specified image file
    var resultFromBarcode = BarcodeReader.Read("myBarcode.Jpeg");

    // Loop through each barcode value read from the image
    foreach (var barcodeValue in resultFromBarcode)
    {
        // Print each barcode value to the console
        Console.WriteLine(barcodeValue);
    }
}
static void Main(string[] args)
{
    // Read barcodes from the specified image file
    var resultFromBarcode = BarcodeReader.Read("myBarcode.Jpeg");

    // Loop through each barcode value read from the image
    foreach (var barcodeValue in resultFromBarcode)
    {
        // Print each barcode value to the console
        Console.WriteLine(barcodeValue);
    }
}
Shared Sub Main(ByVal args() As String)
	' Read barcodes from the specified image file
	Dim resultFromBarcode = BarcodeReader.Read("myBarcode.Jpeg")

	' Loop through each barcode value read from the image
	For Each barcodeValue In resultFromBarcode
		' Print each barcode value to the console
		Console.WriteLine(barcodeValue)
	Next barcodeValue
End Sub
$vbLabelText   $csharpLabel

The above code reads barcodes from the "myBarcode.Jpeg" image file and prints their values to the console. The BarcodeReader class is responsible for decoding the barcode data from the image. The explanation of the code is as follows:

Wyjaśnienie kodu

  • The first line creates a variable named resultFromBarcode. It calls the BarcodeReader.Read method to read barcodes from the image file named "myBarcode.Jpeg". The result of this operation is stored in the resultFromBarcode variable.

  • The second line starts a loop that iterates through each barcode value in the resultFromBarcode collection. The foreach loop allows us to process each barcode value one by one.

  • Inside the loop, this line prints each barcode value to the console. The barcodeValue represents the content of a barcode that was read from the image.

The barcode value will be printed on the Console as shown below.

Wynik

How to Generate Code 128 barcode in C#: Figure 4 - Console output from the read barcode

Analyze Code 128 Encoding Segments

As mentioned earlier, Code 128 uses three character sets — A, B, and C — and switches between them to encode data efficiently. IronBarcode provides the Code128GS1Parser.GetEncodingInfo method to analyze which character sets are used for a given input string.

// Analyze Code 128 encoding segments
var result = Code128GS1Parser.GetEncodingInfo("ABC123456DEF");
Console.WriteLine(result.CharacterSetSummary);  // "B → C → B"
Console.WriteLine(result.TotalSymbols);          // 14
Console.WriteLine(result.IsGS1);                 // false
foreach (var segment in result.Segments)
{
    Console.WriteLine($"{segment.CharacterSetName}: \"{segment.Data}\" ({segment.SymbolCount} symbols)");
}
// Output:
// Code B: "ABC" (3 symbols)
// Code C: "123456" (3 symbols)
// Code B: "DEF" (3 symbols)
// Analyze Code 128 encoding segments
var result = Code128GS1Parser.GetEncodingInfo("ABC123456DEF");
Console.WriteLine(result.CharacterSetSummary);  // "B → C → B"
Console.WriteLine(result.TotalSymbols);          // 14
Console.WriteLine(result.IsGS1);                 // false
foreach (var segment in result.Segments)
{
    Console.WriteLine($"{segment.CharacterSetName}: \"{segment.Data}\" ({segment.SymbolCount} symbols)");
}
// Output:
// Code B: "ABC" (3 symbols)
// Code C: "123456" (3 symbols)
// Code B: "DEF" (3 symbols)
Imports System

' Analyze Code 128 encoding segments
Dim result = Code128GS1Parser.GetEncodingInfo("ABC123456DEF")
Console.WriteLine(result.CharacterSetSummary)  ' "B → C → B"
Console.WriteLine(result.TotalSymbols)         ' 14
Console.WriteLine(result.IsGS1)                ' False
For Each segment In result.Segments
    Console.WriteLine($"{segment.CharacterSetName}: ""{segment.Data}"" ({segment.SymbolCount} symbols)")
Next
' Output:
' Code B: "ABC" (3 symbols)
' Code C: "123456" (3 symbols)
' Code B: "DEF" (3 symbols)
$vbLabelText   $csharpLabel

The method returns a Code128EncodingInfo object containing the breakdown of encoding segments. In this example, the encoder switches from Code B for the letters, to Code C for the numeric pairs (the most compact encoding for digits), and back to Code B for the remaining letters. The TotalSymbols count includes the start symbol, data symbols, code switches, check digit, and stop symbol.

Wnioski

In conclusion, this article has demonstrated how to create a Code 128 barcode generator in C# using the IronBarcode library. By leveraging the capabilities of IronBarcode, developers can easily generate, customize, and style Code 128 barcodes for various applications, including inventory management, product labeling, and shipping. By following this tutorial, developers can integrate robust barcode functionality into their C# projects, enhancing efficiency in handling tasks related to barcode generation and decoding. IronBarcode's versatility and intuitive API make it a valuable tool for developers working on applications that involve barcode implementation.

In the process of generating Code 128 barcodes with the IronBarcode library, developers have the flexibility to customize code set selection characters, ensuring optimal encoding of data with varying ASCII values. The rendering code seamlessly adapts to preferred image formats, offering developers the choice to save barcodes in JPEG or other formats. Additionally, the inclusion of a stop character ensures the accurate termination of encoded information within the generated barcodes.

IronBarcode offers a free trial to unlock the full potential of the library for their development needs. This approach enables developers to assess the capabilities of IronBarcode before committing to the commercial license.

Często Zadawane Pytania

Jak wygenerować barcode Code 128 w języku C#?

Aby wygenerować kod kreskowy Code 128 w języku C#, należy użyć metody BarcodeWriter.CreateBarCode z biblioteki IronBarcode, podając żądany ciąg znaków jako dane wejściowe i określając Code 128 jako typ kodowania. Następnie można wyeksportować wygenerowany obraz kodu kreskowego za pomocą metod takich jak SaveAsJpeg.

Do czego służy Code 128?

Kod 128 służy do kodowania danych alfanumerycznych i znaków specjalnych w kompaktowym formacie BARCODE. Dzięki dużej gęstości danych i wszechstronności idealnie nadaje się do zarządzania zapasami, etykietowania produktów i zastosowań związanych z wysyłką.

Czy mogę dostosować wygląd kodu kreskowego za pomocą IronBarcode?

Tak, można dostosować wygląd BARCODE za pomocą IronBarcode, modyfikując jego kolory za pomocą metod ChangeBackgroundColor i ChangeBarCodeColor oraz zmieniając jego rozmiar za pomocą metody ResizeTo.

Jak odczytać BarCode w języku C#?

Aby odczytać kod kreskowy w języku C#, należy użyć metody BarcodeReader.Read z biblioteki IronBarcode. Metoda ta przetwarza plik obrazu zawierający kod kreskowy i zwraca zdekodowane wartości do dalszego przetwarzania.

Jakie są zalety korzystania z biblioteki IronBarcode do generowania kodów kreskowych?

Biblioteka IronBarcode oferuje przyjazny dla użytkownika interfejs API, obsługuje różne formaty kodów kreskowych, zapewnia automatyczne obliczanie sum kontrolnych oraz umożliwia eksport obrazów w wielu formatach, co czyni ją elastycznym i wydajnym narzędziem do generowania i dostosowywania kodów kreskowych.

Do jakich formatów obrazów może eksportować IronBarcode?

IronBarcode umożliwia eksportowanie obrazów kodów kreskowych do różnych formatów, w tym JPEG, co zapewnia elastyczność w obsłudze i integracji obrazów kodów kreskowych z różnymi aplikacjami.

Czy przed zakupem można wypróbować IronBarcode?

Tak, możesz wypróbować bezpłatną wersję próbną IronBarcode, aby poznać jej pełen potencjał i możliwości przed zakupem licencji komercyjnej, upewniając się, że możesz skutecznie zintegrować funkcjonalność kodów kreskowych ze swoimi projektami w języku C#.

Jordi Bardia
Inżynier oprogramowania
Jordi jest najbardziej biegły w Pythonie, C# i C++. Kiedy nie wykorzystuje swoich umiejętności w Iron Software, programuje gry. Dzieląc odpowiedzialność za testowanie produktów, rozwój produktów i badania, Jordi wnosi ogromną wartość do ciągłej poprawy produktów. Różnorodne doświadczenia ...
Czytaj więcej

Zespol wsparcia Iron

Jestesmy online 24 godziny, 5 dni w tygodniu.
Czat
Email
Zadzwon do mnie