WPF에서 바코드 이미지 생성 및 표시

바코드에는 기계가 읽을 수 있는 형태로 시각적으로 표시되는 제품 또는 회사에 대한 정보가 포함됩니다. 바코드는 선적 및 재고 관리를 추적하는 데 널리 사용됩니다. WPF 응용 프로그램에서 다양한 유형의 바코드를 쉽게 생성할 수 있습니다. 이 기사에서는 WPF 응용 프로그램에서 바코드 이미지를 생성하고 표시하는 방법을 배웁니다. 언급된 단계를 수행하면 C#에서 자체 WPF 바코드 생성기를 갖게 됩니다. 시작하겠습니다.

이 기사에서는 다음 주제를 다룹니다.

  1. WPF 바코드 생성기 기능
  2. C# 바코드 생성기 API
  3. WPF 바코드 생성기 생성 단계
  4. 추가 옵션으로 바코드 생성
  5. 데모 WPF 바코드 생성기
  6. 소스코드 다운로드

WPF 바코드 생성기의 기능

WPF 바코드 생성기에는 다음과 같은 기능이 있습니다.

  1. 다음 유형의 바코드 기호를 생성합니다.
    • 코드128
    • 코드11
    • 코드39
    • QR
    • 데이터 매트릭스
    • EAN13
    • EAN8
    • ITF14
    • PDF417
  2. 생성된 바코드 이미지를 다음 형식으로 저장합니다.
  3. 생성된 바코드 이미지를 미리 봅니다.

C# 바코드 생성기 API

Aspose.BarCode for .NET API를 사용하여 바코드 이미지를 생성하고 WPF 응용 프로그램에서 미리 봅니다. 다양한 바코드 유형을 생성, 스캔 및 읽을 수 있는 기능이 풍부한 API입니다. 또한 배경 색상, 막대 색상, 회전 각도, x-dimension, 이미지 품질, 해상도, 캡션, 크기 등과 같은 생성된 바코드의 모양을 조작할 수 있습니다.

WPF 바코드 생성기를 만드는 단계

다음 단계에 따라 WPF 응용 프로그램에서 바코드 이미지를 생성하고 표시할 수 있습니다.

  • 먼저 새 프로젝트를 만들고 WPF 응용 프로그램 프로젝트 템플릿을 선택합니다.
Select the project template.

Select the project template.

  • 다음으로 “BarcodeGen"과 같이 프로젝트 이름을 입력합니다.

  • 그런 다음 .NET 프레임워크를 선택한 다음 생성을 선택합니다.

  • 그런 다음 NuGet 패키지 관리자를 열고 .NET용 Aspose.BarCode 패키지를 설치합니다.

.NET용 Aspose.BarCode 설치

.NET용 Aspose.BarCode 설치

  • 그런 다음 새 클래스 Barcode.cs를 추가하여 바코드를 정의합니다.
public class Barcode
{
    public string? Text { get; set; }

    public BaseEncodeType? BarcodeType { get; set; }

    public BarCodeImageFormat ImageType { get; set; }
}
  • 그런 다음 MainWindow.xaml을 열고 아래와 같이 필요한 컨트롤을 추가합니다.
필요한 컨트롤 추가

필요한 컨트롤 추가

MainWindow.xaml의 내용을 다음 스크립트로 바꿀 수도 있습니다.

<Window x:Class="BarcodeGen.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:BarcodeGen"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">

    <Grid Width="800" Height="384">
        <Grid.RowDefinitions>
            <RowDefinition Height="191*"/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <Label Content="Select Barcode Type:" HorizontalAlignment="Left" Margin="10,16,0,0" VerticalAlignment="Top" FontSize="14" FontWeight="Bold"/>
        <ComboBox x:Name="comboBarcodeType" HorizontalAlignment="Left" Margin="10,47,0,305" Width="273" Text="Select Barcode Type" IsReadOnly="True" SelectedIndex="-1" FontSize="14" Height="30">
            <ComboBoxItem Content="Code128"></ComboBoxItem>
            <ComboBoxItem Content="Code11"></ComboBoxItem>
            <ComboBoxItem Content="Code32"></ComboBoxItem>
            <ComboBoxItem Content="QR"></ComboBoxItem>
            <ComboBoxItem Content="DataMatrix"></ComboBoxItem>
            <ComboBoxItem Content="EAN13"></ComboBoxItem>
            <ComboBoxItem Content="EAN8"></ComboBoxItem>
            <ComboBoxItem Content="ITF14"></ComboBoxItem>
            <ComboBoxItem Content="PDF417"></ComboBoxItem>
        </ComboBox>

        <Button Name="btnGenerate" Click="btnGenerate_Click" Content="Generate Barcode" HorizontalAlignment="Left" Margin="10,346,0,0" VerticalAlignment="Top" Height="28" Width="273" FontSize="14" FontWeight="Bold"/>
        <Label Content="Enter Your Text:" HorizontalAlignment="Left" Margin="10,92,0,0" VerticalAlignment="Top" FontSize="14" FontWeight="Bold"/>
        <TextBox Name="tbCodeText" TextWrapping="Wrap" Margin="10,123,517,134" Width="273" Height="125"/>
        <Label Content="Select Image Format:" HorizontalAlignment="Left" Margin="10,253,0,0" VerticalAlignment="Top" FontSize="14" FontWeight="Bold"/>
        <RadioButton Name="rbPng" Content="Png" GroupName="rbImageType" Margin="10,285,739,77" Width="51" Height="20" FontSize="14" IsChecked="True"/>
        <RadioButton Name="rbJpg" Content="Jpeg" GroupName="rbImageType" Margin="121,285,628,77" Width="51" Height="20" FontSize="14"/>
        <RadioButton Name="rbBmp" Content="Bmp" GroupName="rbImageType" Margin="232,285,517,77" Width="51" Height="20" FontSize="14"/>
        <CheckBox Name="cbGenerateWithOptions" Height="20" Margin="10,321,517,41" Content="Generate with Options" />
        <GroupBox Header="View Generated Barcode" Margin="317,0,22,0" FontSize="14" FontWeight="Bold">
            <Image Name="imgDynamic" Margin="6,-6,7,6" Stretch="None"  />
        </GroupBox>
    </Grid>
</Window>
  • 그런 다음 MainWindow.xaml.cs 클래스를 열고 바코드 생성 버튼에 대한 클릭 동작을 처리하는 btnGenerateClick 이벤트를 추가합니다.
private void btnGenerate_Click(object sender, RoutedEventArgs e)
{
    // 기본값을 Png로 설정
    var imageType = "Png";

    // 사용자가 선택한 이미지 형식 가져오기
    if(rbPng.IsChecked == true)
    {
        imageType = rbPng.Content.ToString();
    }
    else if(rbBmp.IsChecked == true)
    {
        imageType = rbBmp.Content.ToString();
    }
    else if(rbJpg.IsChecked == true)
    {
        imageType = rbJpg.Content.ToString();
    }

    // 열거형에서 이미지 형식 가져오기
    var imageFormat = (BarCodeImageFormat)Enum.Parse(typeof(BarCodeImageFormat), imageType.ToString());

    // 기본값을 Code128로 설정
    var encodeType = EncodeTypes.Code128;

    // 사용자가 선택한 바코드 유형 가져오기
    if (!string.IsNullOrEmpty(comboBarcodeType.Text))
    {
        switch (comboBarcodeType.Text)
        {
            case "Code128":
                encodeType = EncodeTypes.Code128;
                break;

            case "ITF14":
                encodeType = EncodeTypes.ITF14;
                break;

            case "EAN13":
                encodeType = EncodeTypes.EAN13;
                break;

            case "Datamatrix":
                encodeType = EncodeTypes.DataMatrix;
                break;

            case "Code32":
                encodeType = EncodeTypes.Code32;
                break;

            case "Code11":
                encodeType = EncodeTypes.Code11;
                break;

            case "PDF417":
                encodeType = EncodeTypes.Pdf417;
                break;

            case "EAN8":
                encodeType = EncodeTypes.EAN8;
                break;

            case "QR":
                encodeType = EncodeTypes.QR;
                break;
        }
    }

    // 바코드 개체 초기화
    Barcode barcode = new Barcode();
    barcode.Text = tbCodeText.Text;
    barcode.BarcodeType = encodeType;
    barcode.ImageType = imageFormat;

    try
    {
        string imagePath = "";

        if (cbGenerateWithOptions.IsChecked == true)
        {
            // 추가 옵션으로 바코드 생성 및 이미지 경로 가져오기
            imagePath = GenerateBarcodeWithOptions(barcode);
        }
        else
        {
            // 바코드 생성 및 이미지 경로 가져오기
            imagePath = GenerateBarcode(barcode);
        }

        // 이미지 표시
        Uri fileUri = new Uri(Path.GetFullPath(imagePath));
        imgDynamic.Source = new BitmapImage(fileUri);
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}
  • 그런 다음 바코드를 생성하는 기능을 추가합니다.
private string GenerateBarcode(Barcode barcode)
{
    // 이미지 경로
    string imagePath = comboBarcodeType.Text + "." + barcode.ImageType;

    // 바코드 생성기 초기화
    BarcodeGenerator generator = new BarcodeGenerator(barcode.BarcodeType, barcode.Text);

    // 이미지 저장
    generator.Save(imagePath, barcode.ImageType);

    return imagePath;
}
  • 마지막으로 애플리케이션을 실행합니다.

추가 옵션으로 바코드 생성

바코드 유형에 특정한 추가 옵션을 사용하여 바코드를 생성할 수도 있습니다. WPF 바코드 생성기에서 옵션이 있는 바코드를 생성하는 확인란을 추가했습니다. 다양한 바코드 유형에 대한 추가 옵션을 지정하는 다음 함수를 호출합니다.

private string GenerateBarcodeWithOptions(Barcode barcode)
{
    // 이미지 경로
    string imagePath = comboBarcodeType.Text + "." + barcode.ImageType;

    // 바코드 생성기 초기화
    BarcodeGenerator generator = new BarcodeGenerator(barcode.BarcodeType, barcode.Text);

    if(barcode.BarcodeType == EncodeTypes.QR)
    {
        generator.Parameters.Barcode.XDimension.Pixels = 4;
        //자동 버전 설정
        generator.Parameters.Barcode.QR.QrVersion = QRVersion.Auto;
        //자동 QR 인코딩 유형 설정
        generator.Parameters.Barcode.QR.QrEncodeType = QREncodeType.Auto;
    } 
    else if(barcode.BarcodeType == EncodeTypes.Pdf417)
    {
        generator.Parameters.Barcode.XDimension.Pixels = 2;
        generator.Parameters.Barcode.Pdf417.Columns = 3;
    }
    else if(barcode.BarcodeType == EncodeTypes.DataMatrix)
    {
        //DataMatrix ECC를 140으로 설정
        generator.Parameters.Barcode.DataMatrix.DataMatrixEcc = DataMatrixEccType.Ecc200;
    }
    else if(barcode.BarcodeType == EncodeTypes.Code32)
    {
        generator.Parameters.Barcode.XDimension.Millimeters = 1f;
    }
    else
    {
        generator.Parameters.Barcode.XDimension.Pixels = 2;
        //BarHeight 40 설정
        generator.Parameters.Barcode.BarHeight.Pixels = 40;
    }

    // 이미지 저장
    generator.Save(imagePath, barcode.ImageType);

    return imagePath;
}

문서에서 바코드 유형에 대한 세대 세부 사항에 대해 자세히 읽을 수 있습니다.

데모 WPF 바코드 생성기

다음은 방금 만든 WPF 바코드 생성기 응용 프로그램의 데모입니다.

데모 WPF 바코드 생성기

데모 WPF 바코드 생성기

소스 코드 다운로드

GitHub에서 WPF 바코드 생성기 애플리케이션의 전체 소스 코드를 다운로드할 수 있습니다.

무료 라이선스 받기

평가 제한 없이 라이브러리를 사용해 보려면 무료 임시 라이센스를 얻으십시오.

결론

이 기사에서는 WPF 애플리케이션에서 다양한 유형의 바코드를 생성하는 방법을 배웠습니다. 또한 생성된 바코드 이미지를 프로그래밍 방식으로 미리 보는 방법도 살펴보았습니다. 또한 문서를 사용하여 .NET API용 Aspose.BarCode에 대해 자세히 알아볼 수 있습니다. 모호한 점이 있는 경우 포럼에서 언제든지 문의해 주십시오.

또한보십시오