C# QR 코드 생성기 애플리케이션
IronQR은 Iron Software의 최신 .NET QR 코드 라이브러리입니다. 최신 기계 학습 기법을 활용하여 어떤 각도에서도 높은 정확도로 QR 코드를 읽을 수 있습니다. 새로운 QR 코드를 손쉽게 생성하고 맞춤 설정하세요. 지금 IronQR로 시작하세요.
C#를 사용하여 QR 코드를 만드는 가이드에 오신 것을 환영합니다! QR 코드와 .NET 바코드 DLL은 정보를 빠르고 효율적으로 공유하는 데 널리 사용되는 방법이 되었습니다. 앱을 개발하든, 웹사이트를 관리하든, 아니면 단순히 링크를 깔끔하게 공유할 방법을 찾고 있든, 이러한 코드는 매우 유용할 수 있습니다. 이 가이드에서는 IronQR를 사용하여 QR 코드를 효율적으로 생성하는 방법을 시연할 것이며, 필요에 맞는 QR 코드를 생성할 수 있도록 보장합니다. 이 라이브러리를 사용하면 C# 개발자라면 누구나 복잡한 로직 없이 쉽게 QR 코드를 생성할 수 있습니다. 시작하는 데 필요한 모든 것을 갖추도록 단계별로 안내해 드리겠습니다. 앱에 QR 코드 생성기 기능을 추가하고 싶거나, 단순히 그 방법이 궁금하다면 제대로 찾아오셨습니다. 자, 시작해 볼까요?
C#으로 QR 코드 생성기를 만드는 방법
- Visual Studio에서 Windows Forms 애플리케이션 만들기
- NuGet을 사용하여 QR 라이브러리 설치
- 폼의 프런트엔드 요소 디자인
- QR 코드 생성 로직 작성
- 애플리케이션을 실행하고 QR 코드 생성 시작
C#에서 QR 코드 생성기 라이브러리 설치하기
오늘 무료 체험으로 프로젝트에서 IronQR 사용을 시작하십시오.
시작하기 전에 IronQR NuGet 패키지를 설치해야 합니다.
IronQR: C# QR 라이브러리
IronQR는 QR 코드 기능을 .NET 애플리케이션에 통합하기 위한 C# QR 코드 라이브러리입니다. IronQR은 C#, VB.NET, F#, .NET Core, .NET Standard, .NET Framework 등 다양한 .NET 버전 및 프로젝트 유형을 지원하여 Windows, Linux, macOS, iOS, Android 등 다양한 개발 환경과의 호환성을 보장합니다.
IronQR은 QR 코드를 읽고 QR 코드를 생성하는 기능과 여러 이미지 형식 지원, QR 코드에 크기 조정, 스타일링, 로고 추가 등의 맞춤 옵션을 포함한 고급 기능으로 차별화됩니다.
IronQR의 주요 기능
IronQR은 기본적인 QR 코드 생성 기능을 넘어 다양한 QR 코드 관련 작업을 처리할 수 있도록 설계된 여러 기능을 제공합니다. 이제 이러한 기능들을 살펴보고, 콘솔 앱과 같은 모든 유형의 .NET 애플리케이션 템플릿에 통합할 수 있는 예제 코드를 확인해 보겠습니다.
QR 코드 읽기
IronQR은 QR 코드 디코딩에 탁월하여 사용자가 QR 코드에 포함된 정보에 간편하게 접근할 수 있도록 해줍니다. QR 코드에서 간단한 URL부터 복잡하게 삽입된 정보까지 다양한 데이터를 빠르고 정확하게 추출할 수 있습니다.
using IronQr;
using IronSoftware.Drawing;
using System;
using System.Collections.Generic;
IronQr.License.LicenseKey = "License-Key";
// Load the image file that contains the QR Code
var inputImage = AnyBitmap.FromFile("QRCode.png");
// Prepare the image for QR code detection
QrImageInput qrInput = new QrImageInput(inputImage);
// Initialize the QR Code reader
QrReader qrReader = new QrReader();
// Execute QR Code reading on the provided image
IEnumerable<QrResult> qrResults = qrReader.Read(qrInput);
// Assuming you have the QR results in qrResults as before
foreach (var result in qrResults)
{
Console.WriteLine(result.Value); // Print the QR code content to the console
}Imports IronQr
Imports IronSoftware.Drawing
Imports System
Imports System.Collections.Generic
IronQr.License.LicenseKey = "License-Key"
' Load the image file that contains the QR Code
Dim inputImage = AnyBitmap.FromFile("QRCode.png")
' Prepare the image for QR code detection
Dim qrInput As New QrImageInput(inputImage)
' Initialize the QR Code reader
Dim qrReader As New QrReader()
' Execute QR Code reading on the provided image
Dim qrResults As IEnumerable(Of QrResult) = qrReader.Read(qrInput)
' Assuming you have the QR results in qrResults as before
For Each result In qrResults
Console.WriteLine(result.Value) ' Print the QR code content to the console
Next resultImports IronQr
Imports IronSoftware.Drawing
Imports System
Imports System.Collections.Generic
IronQr.License.LicenseKey = "License-Key"
' Load the image file that contains the QR Code
Dim inputImage = AnyBitmap.FromFile("QRCode.png")
' Prepare the image for QR code detection
Dim qrInput As New QrImageInput(inputImage)
' Initialize the QR Code reader
Dim qrReader As New QrReader()
' Execute QR Code reading on the provided image
Dim qrResults As IEnumerable(Of QrResult) = qrReader.Read(qrInput)
' Assuming you have the QR results in qrResults as before
For Each result In qrResults
Console.WriteLine(result.Value) ' Print the QR code content to the console
Next result먼저 필요한 네임스페이스인 IronQr과 IronSoftware.Drawing을 포함합니다. 이미지 처리를 위해 IronSoftware.Drawing 네임스페이스의 Color도 사용합니다.
QR 코드 읽기를 시작하기 전에, 소프트웨어를 활성화하려면 라이선스 키를 IronQr.License.LicenseKey에 할당해야 합니다. 그런 다음 코드가 AnyBitmap.FromFile("QRCode.png")를 사용하여 파일에서 QR 코드 이미지를 로드합니다.
이미지가 로드되면 다음 단계는 QR 코드 감지를 위해 이미지를 준비하는 것입니다. 이 준비는 이미지를 위한 컨테이너 역할을 하는 QrImageInput 객체를 생성함으로써 이루어집니다.
이 기능의 핵심은 QR 코드 읽기 작업을 수행하도록 생성 및 사용되는 QrReader 클래스에 있습니다. 판독기는 준비된 이미지를 분석하여 이미지에 포함된 QR 코드를 찾습니다. 이 작업의 결과는 이미지 내에서 감지된 QR 코드를 각각 나타내는 QrResult 객체의 집합입니다.
QR 코드에 인코딩된 데이터에 접근하고 이를 활용하기 위해 코드에서는 foreach 루프로 결과 모음을 순회합니다. 각 QrResult 객체에는 QR 코드의 값 등 접근하여 표시할 수 있는 속성이 포함되어 있습니다.
사용자 지정 QR 읽기 모드 옵션
IronQR은 QR 코드를 읽는 다양한 모드를 제공하여 여러 가지 요구 사항에 맞춰 사용할 수 있습니다.
- 혼합 스캔 모드: 명확하지 않거나 부분적으로 숨겨진 QR 코드에 유용하며 속도와 정확성을 균형있게 유지합니다.
- 기계 학습(ML) 스캔 모드: 손상되었거나 읽기 어려운 QR 코드를 읽기 위해 고급 기술을 사용하며, 감지하기 어려운 시나리오에 이상적입니다.
- 기본 스캔 모드: 명확하고 간단한 QR 코드에 대해 가장 쉽고 빠른 방법입니다.
using IronQr;
using IronQr.Enum;
using IronSoftware.Drawing;
using System.Collections.Generic;
IronQr.License.LicenseKey = "License-Key";
// Load the image file that contains the QR Code
var inputImage = AnyBitmap.FromFile("QRCode.png");
QrImageInput mixedScanInput = new QrImageInput(inputImage, QrScanMode.OnlyDetectionModel);
IEnumerable<QrResult> mixedScanResults = new QrReader().Read(mixedScanInput);
QrImageInput mlScanInput = new QrImageInput(inputImage, QrScanMode.OnlyDetectionModel);
IEnumerable<QrResult> mlScanResults = new QrReader().Read(mlScanInput);
QrImageInput basicScanInput = new QrImageInput(inputImage, QrScanMode.OnlyBasicScan);
IEnumerable<QrResult> basicScanResults = new QrReader().Read(basicScanInput);using IronQr;
using IronQr.Enum;
using IronSoftware.Drawing;
using System.Collections.Generic;
IronQr.License.LicenseKey = "License-Key";
// Load the image file that contains the QR Code
var inputImage = AnyBitmap.FromFile("QRCode.png");
QrImageInput mixedScanInput = new QrImageInput(inputImage, QrScanMode.OnlyDetectionModel);
IEnumerable<QrResult> mixedScanResults = new QrReader().Read(mixedScanInput);
QrImageInput mlScanInput = new QrImageInput(inputImage, QrScanMode.OnlyDetectionModel);
IEnumerable<QrResult> mlScanResults = new QrReader().Read(mlScanInput);
QrImageInput basicScanInput = new QrImageInput(inputImage, QrScanMode.OnlyBasicScan);
IEnumerable<QrResult> basicScanResults = new QrReader().Read(basicScanInput);Imports IronQr
Imports IronQr.Enum
Imports IronSoftware.Drawing
Imports System.Collections.Generic
IronQr.License.LicenseKey = "License-Key"
' Load the image file that contains the QR Code
Dim inputImage = AnyBitmap.FromFile("QRCode.png")
Dim mixedScanInput As New QrImageInput(inputImage, QrScanMode.OnlyDetectionModel)
Dim mixedScanResults As IEnumerable(Of QrResult) = (New QrReader()).Read(mixedScanInput)
Dim mlScanInput As New QrImageInput(inputImage, QrScanMode.OnlyDetectionModel)
Dim mlScanResults As IEnumerable(Of QrResult) = (New QrReader()).Read(mlScanInput)
Dim basicScanInput As New QrImageInput(inputImage, QrScanMode.OnlyBasicScan)
Dim basicScanResults As IEnumerable(Of QrResult) = (New QrReader()).Read(basicScanInput)Imports IronQr
Imports IronQr.Enum
Imports IronSoftware.Drawing
Imports System.Collections.Generic
IronQr.License.LicenseKey = "License-Key"
' Load the image file that contains the QR Code
Dim inputImage = AnyBitmap.FromFile("QRCode.png")
Dim mixedScanInput As New QrImageInput(inputImage, QrScanMode.OnlyDetectionModel)
Dim mixedScanResults As IEnumerable(Of QrResult) = (New QrReader()).Read(mixedScanInput)
Dim mlScanInput As New QrImageInput(inputImage, QrScanMode.OnlyDetectionModel)
Dim mlScanResults As IEnumerable(Of QrResult) = (New QrReader()).Read(mlScanInput)
Dim basicScanInput As New QrImageInput(inputImage, QrScanMode.OnlyBasicScan)
Dim basicScanResults As IEnumerable(Of QrResult) = (New QrReader()).Read(basicScanInput)고급 QR 코드 읽기
IronQR의 고급 QR 코드 판독 기능은 QR 코드 스캔 및 디코딩에 대한 포괄적인 접근 방식을 제공합니다. 이 기능 세트는 기본적인 읽기 기능을 넘어 더욱 심층적인 상호 작용과 데이터 추출 기능을 제공합니다.
using IronQr;
using IronSoftware.Drawing;
using System;
using System.Collections.Generic;
IronQr.License.LicenseKey = "License-Key";
var imageToScan = AnyBitmap.FromFile("QRCode.png");
QrImageInput qrInput = new QrImageInput(imageToScan);
QrReader qrScanner = new QrReader();
IEnumerable<QrResult> scanResults = qrScanner.Read(qrInput);
foreach (QrResult qrResult in scanResults)
{
Console.WriteLine(qrResult.Value);
Console.WriteLine(qrResult.Url);
foreach (IronSoftware.Drawing.PointF coordinate in qrResult.Points)
{
Console.WriteLine($"{coordinate.X}, {coordinate.Y}");
}
}using IronQr;
using IronSoftware.Drawing;
using System;
using System.Collections.Generic;
IronQr.License.LicenseKey = "License-Key";
var imageToScan = AnyBitmap.FromFile("QRCode.png");
QrImageInput qrInput = new QrImageInput(imageToScan);
QrReader qrScanner = new QrReader();
IEnumerable<QrResult> scanResults = qrScanner.Read(qrInput);
foreach (QrResult qrResult in scanResults)
{
Console.WriteLine(qrResult.Value);
Console.WriteLine(qrResult.Url);
foreach (IronSoftware.Drawing.PointF coordinate in qrResult.Points)
{
Console.WriteLine($"{coordinate.X}, {coordinate.Y}");
}
}Imports IronQr
Imports IronSoftware.Drawing
Imports System
Imports System.Collections.Generic
IronQr.License.LicenseKey = "License-Key"
Dim imageToScan = AnyBitmap.FromFile("QRCode.png")
Dim qrInput As New QrImageInput(imageToScan)
Dim qrScanner As New QrReader()
Dim scanResults As IEnumerable(Of QrResult) = qrScanner.Read(qrInput)
For Each qrResult As QrResult In scanResults
Console.WriteLine(qrResult.Value)
Console.WriteLine(qrResult.Url)
For Each coordinate As IronSoftware.Drawing.PointF In qrResult.Points
Console.WriteLine($"{coordinate.X}, {coordinate.Y}")
Next coordinate
Next qrResultImports IronQr
Imports IronSoftware.Drawing
Imports System
Imports System.Collections.Generic
IronQr.License.LicenseKey = "License-Key"
Dim imageToScan = AnyBitmap.FromFile("QRCode.png")
Dim qrInput As New QrImageInput(imageToScan)
Dim qrScanner As New QrReader()
Dim scanResults As IEnumerable(Of QrResult) = qrScanner.Read(qrInput)
For Each qrResult As QrResult In scanResults
Console.WriteLine(qrResult.Value)
Console.WriteLine(qrResult.Url)
For Each coordinate As IronSoftware.Drawing.PointF In qrResult.Points
Console.WriteLine($"{coordinate.X}, {coordinate.Y}")
Next coordinate
Next qrResultC# 애플리케이션에서 IronQR 라이브러리를 사용하여 QR 코드 생성기를 만들려면 다음 단계를 주의 깊게 따르십시오. 이 가이드에서는 Windows 폼 애플리케이션 설정, IronQR 라이브러리 설치, QR 코드 생성 코드 작성 및 출력 결과 해석 과정을 안내합니다.
1단계: Visual Studio에서 Windows 애플리케이션 생성
-
먼저 컴퓨터에서 Visual Studio를 실행하세요.
-
"새 프로젝트 만들기" 버튼을 클릭합니다.
-
프로젝트 유형으로 Windows Forms 앱을 선택합니다. 언어로 C#을 선택했는지 확인하세요.

-
프로젝트 이름을 입력하고 저장할 위치를 선택하세요. 다음 화면에서 .NET Framework를 선택하세요. 그런 다음 만들기를 클릭하세요.

2단계: IronQR 라이브러리 설치
이제 프로젝트에 IronQR 라이브러리를 설치할 차례입니다. IronQR 라이브러리는 다양한 방법으로 설치할 수 있습니다.
NuGet 패키지 관리자를 사용하여 설치하세요.
-
솔루션 탐색기에서 프로젝트를 마우스 오른쪽 버튼으로 클릭하고 NuGet 패키지 관리를 선택합니다.
-
검색 창에
IronQR을 입력하고 Enter 키를 누르세요.
-
목록에서 IronQR을 찾아 옆에 있는 설치를 클릭합니다.

NuGet 패키지 관리자 콘솔을 사용하여 설치하세요.
- 도구 > NuGet 패키지 관리자 > 패키지 관리자 콘솔 로 이동합니다.

Install-Package IronQr를 입력하고 Enter를 누르세요.

3단계: 프런트엔드 디자인

3.1 제목 헤더

QR 코드 생성기 애플리케이션을 실행하면 사용자는 굵고 권위 있는 글꼴로 표시된 "QR Generator IronQR"이라는 눈길을 사로잡는 제목을 즉시 접하게 됩니다.
3.2 입력 섹션
QR 코드 입력란
사용자는 QR 코드에 인코딩할 데이터를 입력할 수 있습니다.
로고 선택

"로고 선택" 영역을 통해 추가적인 맞춤 설정이 가능합니다. 사용자는 QR 코드에 삽입될 로고를 업로드할 수 있습니다.
색상 구성

색상 선택 버튼을 통해 사용자는 QR 코드의 색상 팔레트를 맞춤 설정할 수 있습니다.
3.3 스타일링 매개변수

치수 설정
사용자가 QR 코드의 전체 크기를 지정할 수 있습니다.
여백 설정
사용자가 QR 코드 주변의 공백을 지정할 수 있습니다.
3.4 출력 미리보기
생성된 QR 코드의 실시간 미리보기를 제공합니다.

3.5 액션 버튼
QR 코드 생성
QR 코드 생성 프로세스를 시작합니다.

QR 코드 저장
QR 코드를 저장하기 위한 저장 대화 상자를 엽니다.

양식 초기화
이전 입력 및 선택 사항을 모두 지웁니다.

4단계: 백엔드 로직 작성
4.1 설정 및 초기화
필요한 네임스페이스가 포함됩니다: IronQr 및 IronSoftware.Drawing.
using IronQr;
using IronSoftware.Drawing;
using Color = IronSoftware.Drawing.Color;using IronQr;
using IronSoftware.Drawing;
using Color = IronSoftware.Drawing.Color;Imports IronQr
Imports IronSoftware.Drawing
Imports Color = IronSoftware.Drawing.ColorImports IronQr
Imports IronSoftware.Drawing
Imports Color = IronSoftware.Drawing.Colorpublic QR_Generator()
{
InitializeComponent();
SetLicenseKey();
EnsureDirectoryExists(qrCodesDirectory);
}public QR_Generator()
{
InitializeComponent();
SetLicenseKey();
EnsureDirectoryExists(qrCodesDirectory);
}'INSTANT VB WARNING: The following constructor is declared outside of its associated class:
'ORIGINAL LINE: public QR_Generator()
Public Sub New()
InitializeComponent()
SetLicenseKey()
EnsureDirectoryExists(qrCodesDirectory)
End Sub'INSTANT VB WARNING: The following constructor is declared outside of its associated class:
'ORIGINAL LINE: public QR_Generator()
Public Sub New()
InitializeComponent()
SetLicenseKey()
EnsureDirectoryExists(qrCodesDirectory)
End Sub4.2 라이선스 키 구성
IronQR 라이브러리에 유효한 라이선스 키를 적용합니다.
private static void SetLicenseKey() {
IronQr.License.LicenseKey = "YOUR_LICENSE_KEY";
}private static void SetLicenseKey() {
IronQr.License.LicenseKey = "YOUR_LICENSE_KEY";
}Private Shared Sub SetLicenseKey()
IronQr.License.LicenseKey = "YOUR_LICENSE_KEY"
End SubPrivate Shared Sub SetLicenseKey()
IronQr.License.LicenseKey = "YOUR_LICENSE_KEY"
End Sub"YOUR_LICENSE_KEY"를 실제 라이선스 키로 교체하십시오.
4.3 디렉토리 관리
필요한 디렉터리를 확인하거나 생성합니다.
private static void EnsureDirectoryExists(string path)
{
if (!System.IO.Directory.Exists(path))
{
System.IO.Directory.CreateDirectory(path);
}
}private static void EnsureDirectoryExists(string path)
{
if (!System.IO.Directory.Exists(path))
{
System.IO.Directory.CreateDirectory(path);
}
}Private Shared Sub EnsureDirectoryExists(ByVal path As String)
If Not System.IO.Directory.Exists(path) Then
System.IO.Directory.CreateDirectory(path)
End If
End SubPrivate Shared Sub EnsureDirectoryExists(ByVal path As String)
If Not System.IO.Directory.Exists(path) Then
System.IO.Directory.CreateDirectory(path)
End If
End SubQR 코드 디렉터리 경로는 QR_Generator 클래스 생성자에서 qrCodesDirectory로 정의되며, 애플리케이션의 시작 경로와 "QR Codes" 폴더 이름을 결합한 값입니다:
string qrCodesDirectory = System.IO.Path.Combine(Application.StartupPath, "QR Codes");string qrCodesDirectory = System.IO.Path.Combine(Application.StartupPath, "QR Codes");Dim qrCodesDirectory As String = System.IO.Path.Combine(Application.StartupPath, "QR Codes")Dim qrCodesDirectory As String = System.IO.Path.Combine(Application.StartupPath, "QR Codes")4.4 색상 선택
색상 대화 상자 구성 요소와 유틸리티 함수를 제공합니다.
private string ColorToHex(System.Drawing.Color color)
{
return $"#{color.R:X2}{color.G:X2}{color.B:X2}";
}private string ColorToHex(System.Drawing.Color color)
{
return $"#{color.R:X2}{color.G:X2}{color.B:X2}";
}Private Function ColorToHex(ByVal color As System.Drawing.Color) As String
Return $"#{color.R:X2}{color.G:X2}{color.B:X2}"
End FunctionPrivate Function ColorToHex(ByVal color As System.Drawing.Color) As String
Return $"#{color.R:X2}{color.G:X2}{color.B:X2}"
End FunctionUpdateColor 메소드는 선택한 색을 받아 16진수 문자열을 사용하여 IronSoftware.Drawing.Color 형식으로 변환하며, 선택에 따라 QR 코드의 전경 또는 배경 색상을 업데이트합니다. 또한 새로운 색상 선택을 반영하여 사용자 인터페이스(UI)를 업데이트합니다.
private void UpdateColor(ref Color targetColor, Control display, bool isBackground)
{
if (select_color.ShowDialog() == DialogResult.OK)
{
var hexColor = ColorToHex(select_color.Color);
targetColor = new Color(hexColor);
display.BackColor = select_color.Color;
}
}private void UpdateColor(ref Color targetColor, Control display, bool isBackground)
{
if (select_color.ShowDialog() == DialogResult.OK)
{
var hexColor = ColorToHex(select_color.Color);
targetColor = new Color(hexColor);
display.BackColor = select_color.Color;
}
}Private Sub UpdateColor(ByRef targetColor As Color, ByVal display As Control, ByVal isBackground As Boolean)
If select_color.ShowDialog() = DialogResult.OK Then
Dim hexColor = ColorToHex(select_color.Color)
targetColor = New Color(hexColor)
display.BackColor = select_color.Color
End If
End SubPrivate Sub UpdateColor(ByRef targetColor As Color, ByVal display As Control, ByVal isBackground As Boolean)
If select_color.ShowDialog() = DialogResult.OK Then
Dim hexColor = ColorToHex(select_color.Color)
targetColor = New Color(hexColor)
display.BackColor = select_color.Color
End If
End Sub4.5 로고 추가
사용자가 로고를 선택할 수 있도록 합니다.
private void btn_logo_Click(object sender, EventArgs e)
{
if (select_logo.ShowDialog() == DialogResult.OK)
{
try
{
logoBmp = new AnyBitmap(select_logo.FileName);
selected_logo.Image = Image.FromFile(select_logo.FileName);
}
catch (Exception ex)
{
ShowError("An error occurred while loading the logo", ex.Message);
}
}
}private void btn_logo_Click(object sender, EventArgs e)
{
if (select_logo.ShowDialog() == DialogResult.OK)
{
try
{
logoBmp = new AnyBitmap(select_logo.FileName);
selected_logo.Image = Image.FromFile(select_logo.FileName);
}
catch (Exception ex)
{
ShowError("An error occurred while loading the logo", ex.Message);
}
}
}Private Sub btn_logo_Click(ByVal sender As Object, ByVal e As EventArgs)
If select_logo.ShowDialog() = DialogResult.OK Then
Try
logoBmp = New AnyBitmap(select_logo.FileName)
selected_logo.Image = Image.FromFile(select_logo.FileName)
Catch ex As Exception
ShowError("An error occurred while loading the logo", ex.Message)
End Try
End If
End SubPrivate Sub btn_logo_Click(ByVal sender As Object, ByVal e As EventArgs)
If select_logo.ShowDialog() = DialogResult.OK Then
Try
logoBmp = New AnyBitmap(select_logo.FileName)
selected_logo.Image = Image.FromFile(select_logo.FileName)
Catch ex As Exception
ShowError("An error occurred while loading the logo", ex.Message)
End Try
End If
End Sub4.6 QR 코드 생성
사용자 입력에 따라 QR 코드를 생성하는 로직이 포함되어 있습니다.
private void btn_generate_Click(object sender, EventArgs e)
{
GenerateQRCode();
}private void btn_generate_Click(object sender, EventArgs e)
{
GenerateQRCode();
}Private Sub btn_generate_Click(ByVal sender As Object, ByVal e As EventArgs)
GenerateQRCode()
End SubPrivate Sub btn_generate_Click(ByVal sender As Object, ByVal e As EventArgs)
GenerateQRCode()
End SubQrOptions 객체는 오류 정정 수준을 정의하여 QR 코드가 손상되거나 가려져도 읽을 수 있는 능력을 높입니다. CreateStyleOptions 메서드는 색상, 크기, 로고 등 사용자의 맞춤 설정을 포함하는 QrStyleOptions 객체를 생성합니다. 이 메서드의 자세한 내용은 다음과 같습니다.
private QrStyleOptions CreateStyleOptions()
{
return new QrStyleOptions
{
BackgroundColor = bgColor,
Color = color,
Dimensions = txt_dimension.Value > 0 ? Convert.ToInt32(txt_dimension.Value) : throw new ArgumentException("Please select valid dimensions!"),
Margins = Convert.ToInt32(txt_margin.Value),
Logo = logoBmp != null ? new QrLogo { Bitmap = logoBmp, Width = 50, Height = 50, CornerRadius = 5 } : null
};
}private QrStyleOptions CreateStyleOptions()
{
return new QrStyleOptions
{
BackgroundColor = bgColor,
Color = color,
Dimensions = txt_dimension.Value > 0 ? Convert.ToInt32(txt_dimension.Value) : throw new ArgumentException("Please select valid dimensions!"),
Margins = Convert.ToInt32(txt_margin.Value),
Logo = logoBmp != null ? new QrLogo { Bitmap = logoBmp, Width = 50, Height = 50, CornerRadius = 5 } : null
};
}Private Function CreateStyleOptions() As QrStyleOptions
'INSTANT VB TODO TASK: Throw expressions are not converted by Instant VB:
'ORIGINAL LINE: return new QrStyleOptions { BackgroundColor = bgColor, Color = color, Dimensions = txt_dimension.Value > 0 ? Convert.ToInt32(txt_dimension.Value) : throw new ArgumentException("Please select valid dimensions!"), Margins = Convert.ToInt32(txt_margin.Value), Logo = logoBmp != null ? new QrLogo { Bitmap = logoBmp, Width = 50, Height = 50, CornerRadius = 5 } : null };
Return New QrStyleOptions With {
.BackgroundColor = bgColor,
.Color = color,
.Dimensions = If(txt_dimension.Value > 0, Convert.ToInt32(txt_dimension.Value), throw New ArgumentException("Please select valid dimensions!")),
.Margins = Convert.ToInt32(txt_margin.Value),
.Logo = If(logoBmp IsNot Nothing, New QrLogo With {
.Bitmap = logoBmp,
.Width = 50,
.Height = 50,
.CornerRadius = 5
}, Nothing)
}
End FunctionPrivate Function CreateStyleOptions() As QrStyleOptions
'INSTANT VB TODO TASK: Throw expressions are not converted by Instant VB:
'ORIGINAL LINE: return new QrStyleOptions { BackgroundColor = bgColor, Color = color, Dimensions = txt_dimension.Value > 0 ? Convert.ToInt32(txt_dimension.Value) : throw new ArgumentException("Please select valid dimensions!"), Margins = Convert.ToInt32(txt_margin.Value), Logo = logoBmp != null ? new QrLogo { Bitmap = logoBmp, Width = 50, Height = 50, CornerRadius = 5 } : null };
Return New QrStyleOptions With {
.BackgroundColor = bgColor,
.Color = color,
.Dimensions = If(txt_dimension.Value > 0, Convert.ToInt32(txt_dimension.Value), throw New ArgumentException("Please select valid dimensions!")),
.Margins = Convert.ToInt32(txt_margin.Value),
.Logo = If(logoBmp IsNot Nothing, New QrLogo With {
.Bitmap = logoBmp,
.Width = 50,
.Height = 50,
.CornerRadius = 5
}, Nothing)
}
End Function4.7 QR 코드 저장하기
생성된 QR 코드를 저장하는 기능을 처리합니다.
private void btn_save_Click(object sender, EventArgs e)
{
SaveQRCode();
}
private void SaveQRCode()
{
if (pictureBox.Image == null)
{
MessageBox.Show("There is no QR code to save.", "Error");
return;
}
saveFileDialog.Filter = "PNG Files|*.png|JPEG Files|*.jpg";
saveFileDialog.Title = "Save QR Code";
saveFileDialog.FileName = "QRCode";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
pictureBox.Image.Save(saveFileDialog.FileName, DetermineImageFormat(saveFileDialog.FileName));
MessageBox.Show("QR Code has been saved!", "Success");
}
catch (Exception ex)
{
ShowError("An error occurred while saving the QR code", ex.Message);
}
}
}private void btn_save_Click(object sender, EventArgs e)
{
SaveQRCode();
}
private void SaveQRCode()
{
if (pictureBox.Image == null)
{
MessageBox.Show("There is no QR code to save.", "Error");
return;
}
saveFileDialog.Filter = "PNG Files|*.png|JPEG Files|*.jpg";
saveFileDialog.Title = "Save QR Code";
saveFileDialog.FileName = "QRCode";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
pictureBox.Image.Save(saveFileDialog.FileName, DetermineImageFormat(saveFileDialog.FileName));
MessageBox.Show("QR Code has been saved!", "Success");
}
catch (Exception ex)
{
ShowError("An error occurred while saving the QR code", ex.Message);
}
}
}Private Sub btn_save_Click(ByVal sender As Object, ByVal e As EventArgs)
SaveQRCode()
End Sub
Private Sub SaveQRCode()
If pictureBox.Image Is Nothing Then
MessageBox.Show("There is no QR code to save.", "Error")
Return
End If
saveFileDialog.Filter = "PNG Files|*.png|JPEG Files|*.jpg"
saveFileDialog.Title = "Save QR Code"
saveFileDialog.FileName = "QRCode"
If saveFileDialog.ShowDialog() = DialogResult.OK Then
Try
pictureBox.Image.Save(saveFileDialog.FileName, DetermineImageFormat(saveFileDialog.FileName))
MessageBox.Show("QR Code has been saved!", "Success")
Catch ex As Exception
ShowError("An error occurred while saving the QR code", ex.Message)
End Try
End If
End SubPrivate Sub btn_save_Click(ByVal sender As Object, ByVal e As EventArgs)
SaveQRCode()
End Sub
Private Sub SaveQRCode()
If pictureBox.Image Is Nothing Then
MessageBox.Show("There is no QR code to save.", "Error")
Return
End If
saveFileDialog.Filter = "PNG Files|*.png|JPEG Files|*.jpg"
saveFileDialog.Title = "Save QR Code"
saveFileDialog.FileName = "QRCode"
If saveFileDialog.ShowDialog() = DialogResult.OK Then
Try
pictureBox.Image.Save(saveFileDialog.FileName, DetermineImageFormat(saveFileDialog.FileName))
MessageBox.Show("QR Code has been saved!", "Success")
Catch ex As Exception
ShowError("An error occurred while saving the QR code", ex.Message)
End Try
End If
End Subprivate System.Drawing.Imaging.ImageFormat DetermineImageFormat(string filePath)
{
return System.IO.Path.GetExtension(filePath).ToLower() == ".jpg" ? System.Drawing.Imaging.ImageFormat.Jpeg : System.Drawing.Imaging.ImageFormat.Png;
}private System.Drawing.Imaging.ImageFormat DetermineImageFormat(string filePath)
{
return System.IO.Path.GetExtension(filePath).ToLower() == ".jpg" ? System.Drawing.Imaging.ImageFormat.Jpeg : System.Drawing.Imaging.ImageFormat.Png;
}Private Function DetermineImageFormat(ByVal filePath As String) As System.Drawing.Imaging.ImageFormat
Return If(System.IO.Path.GetExtension(filePath).ToLower() = ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg, System.Drawing.Imaging.ImageFormat.Png)
End FunctionPrivate Function DetermineImageFormat(ByVal filePath As String) As System.Drawing.Imaging.ImageFormat
Return If(System.IO.Path.GetExtension(filePath).ToLower() = ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg, System.Drawing.Imaging.ImageFormat.Png)
End Function4.8 애플리케이션 재설정
사용자 입력을 지우고 폼 상태를 초기화합니다.
private void btn_reset_Click(object sender, EventArgs e)
{
ResetFields();
}
private void ResetFields()
{
txt_QR.Text = string.Empty;
txt_dimension.Value = 200;
txt_margin.Value = 0;
bgColor = Color.White;
color = Color.Black;
txt_selected_color.BackColor = System.Drawing.Color.White;
txt_selected_bgcolor.BackColor = System.Drawing.Color.Black;
logoBmp = null;
selected_logo.Image = null;
pictureBox.Image = null;
}private void btn_reset_Click(object sender, EventArgs e)
{
ResetFields();
}
private void ResetFields()
{
txt_QR.Text = string.Empty;
txt_dimension.Value = 200;
txt_margin.Value = 0;
bgColor = Color.White;
color = Color.Black;
txt_selected_color.BackColor = System.Drawing.Color.White;
txt_selected_bgcolor.BackColor = System.Drawing.Color.Black;
logoBmp = null;
selected_logo.Image = null;
pictureBox.Image = null;
}Private Sub btn_reset_Click(ByVal sender As Object, ByVal e As EventArgs)
ResetFields()
End Sub
Private Sub ResetFields()
txt_QR.Text = String.Empty
txt_dimension.Value = 200
txt_margin.Value = 0
bgColor = Color.White
color = Color.Black
txt_selected_color.BackColor = System.Drawing.Color.White
txt_selected_bgcolor.BackColor = System.Drawing.Color.Black
logoBmp = Nothing
selected_logo.Image = Nothing
pictureBox.Image = Nothing
End SubPrivate Sub btn_reset_Click(ByVal sender As Object, ByVal e As EventArgs)
ResetFields()
End Sub
Private Sub ResetFields()
txt_QR.Text = String.Empty
txt_dimension.Value = 200
txt_margin.Value = 0
bgColor = Color.White
color = Color.Black
txt_selected_color.BackColor = System.Drawing.Color.White
txt_selected_bgcolor.BackColor = System.Drawing.Color.Black
logoBmp = Nothing
selected_logo.Image = Nothing
pictureBox.Image = Nothing
End Sub4.9 오류 처리
사용자에게 오류 메시지를 표시합니다.
private static void ShowError(string title, string message)
{
MessageBox.Show($"{title}: {message}", "Error");
}private static void ShowError(string title, string message)
{
MessageBox.Show($"{title}: {message}", "Error");
}Private Shared Sub ShowError(ByVal title As String, ByVal message As String)
MessageBox.Show($"{title}: {message}", "Error")
End SubPrivate Shared Sub ShowError(ByVal title As String, ByVal message As String)
MessageBox.Show($"{title}: {message}", "Error")
End Sub4.10 전체 코드 예제
위의 모든 기능을 결합한 전체 코드는 프로젝트에 링크된 예제 파일에서 확인할 수 있습니다.
using IronQr;
using IronSoftware.Drawing;
using Color = IronSoftware.Drawing.Color;
namespace IronQR_QR_Generator_WinForms
{
public partial class QR_Generator : Form
{
string qrCodesDirectory = System.IO.Path.Combine(Application.StartupPath, "QR Codes");
Color bgColor = Color.White;
Color color = Color.Black;
AnyBitmap? logoBmp = null;
public QR_Generator()
{
InitializeComponent();
SetLicenseKey();
EnsureDirectoryExists(qrCodesDirectory);
}
private static void SetLicenseKey()
{
IronQr.License.LicenseKey = "License-Key";
}
private static void EnsureDirectoryExists(string path)
{
if (!System.IO.Directory.Exists(path))
{
System.IO.Directory.CreateDirectory(path);
}
}
private void btn_color_Click(object sender, EventArgs e)
{
UpdateColor(ref color, txt_selected_color, false);
}
private void btn_background_Click(object sender, EventArgs e)
{
UpdateColor(ref bgColor, txt_selected_bgcolor, true);
}
private string ColorToHex(System.Drawing.Color color)
{
return $"#{color.R:X2}{color.G:X2}{color.B:X2}";
}
private void UpdateColor(ref Color targetColor, Control display, bool isBackground)
{
if (select_color.ShowDialog() == DialogResult.OK)
{
var hexColor = ColorToHex(select_color.Color);
targetColor = new Color(hexColor);
display.BackColor = select_color.Color;
}
}
private void btn_logo_Click(object sender, EventArgs e)
{
if (select_logo.ShowDialog() == DialogResult.OK)
{
try
{
logoBmp = new AnyBitmap(select_logo.FileName);
selected_logo.Image = Image.FromFile(select_logo.FileName);
}
catch (Exception ex)
{
ShowError("An error occurred while loading the logo", ex.Message);
}
}
}
private void btn_generate_Click(object sender, EventArgs e)
{
GenerateQRCode();
}
private void GenerateQRCode()
{
try
{
var options = new QrOptions(QrErrorCorrectionLevel.High);
var myQr = QrWriter.Write(txt_QR.Text, options);
var style = CreateStyleOptions();
var qrImage = myQr.Save(style);
var fileName = $"{DateTime.Now:yyyyMMddHHmmssfff}_QR.png";
var fullPath = System.IO.Path.Combine(qrCodesDirectory, fileName);
qrImage.SaveAs(fullPath);
pictureBox.Image = Image.FromFile(fullPath);
}
catch (Exception ex)
{
ShowError("An error occurred during QR code generation or saving", ex.Message);
}
}
private QrStyleOptions CreateStyleOptions()
{
return new QrStyleOptions
{
BackgroundColor = bgColor,
Color = color,
Dimensions = txt_dimension.Value > 0 ? Convert.ToInt32(txt_dimension.Value) : throw new ArgumentException("Please select valid dimensions!"),
Margins = Convert.ToInt32(txt_margin.Value),
Logo = logoBmp != null ? new QrLogo { Bitmap = logoBmp, Width = 50, Height = 50, CornerRadius = 5 } : null
};
}
private void btn_save_Click(object sender, EventArgs e)
{
SaveQRCode();
}
private void SaveQRCode()
{
if (pictureBox.Image == null)
{
MessageBox.Show("There is no QR code to save.", "Error");
return;
}
saveFileDialog.Filter = "PNG Files|*.png|JPEG Files|*.jpg";
saveFileDialog.Title = "Save QR Code";
saveFileDialog.FileName = "QRCode";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
pictureBox.Image.Save(saveFileDialog.FileName, DetermineImageFormat(saveFileDialog.FileName));
MessageBox.Show("QR Code has been saved!", "Success");
}
catch (Exception ex)
{
ShowError("An error occurred while saving the QR code", ex.Message);
}
}
}
private System.Drawing.Imaging.ImageFormat DetermineImageFormat(string filePath)
{
return System.IO.Path.GetExtension(filePath).ToLower() == ".jpg" ? System.Drawing.Imaging.ImageFormat.Jpeg : System.Drawing.Imaging.ImageFormat.Png;
}
private void btn_reset_Click(object sender, EventArgs e)
{
ResetFields();
}
private void ResetFields()
{
txt_QR.Text = string.Empty;
txt_dimension.Value = 200;
txt_margin.Value = 0;
bgColor = Color.White;
color = Color.Black;
txt_selected_color.BackColor = bgColor;
txt_selected_bgcolor.BackColor = color;
logoBmp = null;
selected_logo.Image = null;
pictureBox.Image = null;
}
private static void ShowError(string title, string message)
{
MessageBox.Show($"{title}: {message}", "Error");
}
}
}using IronQr;
using IronSoftware.Drawing;
using Color = IronSoftware.Drawing.Color;
namespace IronQR_QR_Generator_WinForms
{
public partial class QR_Generator : Form
{
string qrCodesDirectory = System.IO.Path.Combine(Application.StartupPath, "QR Codes");
Color bgColor = Color.White;
Color color = Color.Black;
AnyBitmap? logoBmp = null;
public QR_Generator()
{
InitializeComponent();
SetLicenseKey();
EnsureDirectoryExists(qrCodesDirectory);
}
private static void SetLicenseKey()
{
IronQr.License.LicenseKey = "License-Key";
}
private static void EnsureDirectoryExists(string path)
{
if (!System.IO.Directory.Exists(path))
{
System.IO.Directory.CreateDirectory(path);
}
}
private void btn_color_Click(object sender, EventArgs e)
{
UpdateColor(ref color, txt_selected_color, false);
}
private void btn_background_Click(object sender, EventArgs e)
{
UpdateColor(ref bgColor, txt_selected_bgcolor, true);
}
private string ColorToHex(System.Drawing.Color color)
{
return $"#{color.R:X2}{color.G:X2}{color.B:X2}";
}
private void UpdateColor(ref Color targetColor, Control display, bool isBackground)
{
if (select_color.ShowDialog() == DialogResult.OK)
{
var hexColor = ColorToHex(select_color.Color);
targetColor = new Color(hexColor);
display.BackColor = select_color.Color;
}
}
private void btn_logo_Click(object sender, EventArgs e)
{
if (select_logo.ShowDialog() == DialogResult.OK)
{
try
{
logoBmp = new AnyBitmap(select_logo.FileName);
selected_logo.Image = Image.FromFile(select_logo.FileName);
}
catch (Exception ex)
{
ShowError("An error occurred while loading the logo", ex.Message);
}
}
}
private void btn_generate_Click(object sender, EventArgs e)
{
GenerateQRCode();
}
private void GenerateQRCode()
{
try
{
var options = new QrOptions(QrErrorCorrectionLevel.High);
var myQr = QrWriter.Write(txt_QR.Text, options);
var style = CreateStyleOptions();
var qrImage = myQr.Save(style);
var fileName = $"{DateTime.Now:yyyyMMddHHmmssfff}_QR.png";
var fullPath = System.IO.Path.Combine(qrCodesDirectory, fileName);
qrImage.SaveAs(fullPath);
pictureBox.Image = Image.FromFile(fullPath);
}
catch (Exception ex)
{
ShowError("An error occurred during QR code generation or saving", ex.Message);
}
}
private QrStyleOptions CreateStyleOptions()
{
return new QrStyleOptions
{
BackgroundColor = bgColor,
Color = color,
Dimensions = txt_dimension.Value > 0 ? Convert.ToInt32(txt_dimension.Value) : throw new ArgumentException("Please select valid dimensions!"),
Margins = Convert.ToInt32(txt_margin.Value),
Logo = logoBmp != null ? new QrLogo { Bitmap = logoBmp, Width = 50, Height = 50, CornerRadius = 5 } : null
};
}
private void btn_save_Click(object sender, EventArgs e)
{
SaveQRCode();
}
private void SaveQRCode()
{
if (pictureBox.Image == null)
{
MessageBox.Show("There is no QR code to save.", "Error");
return;
}
saveFileDialog.Filter = "PNG Files|*.png|JPEG Files|*.jpg";
saveFileDialog.Title = "Save QR Code";
saveFileDialog.FileName = "QRCode";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
pictureBox.Image.Save(saveFileDialog.FileName, DetermineImageFormat(saveFileDialog.FileName));
MessageBox.Show("QR Code has been saved!", "Success");
}
catch (Exception ex)
{
ShowError("An error occurred while saving the QR code", ex.Message);
}
}
}
private System.Drawing.Imaging.ImageFormat DetermineImageFormat(string filePath)
{
return System.IO.Path.GetExtension(filePath).ToLower() == ".jpg" ? System.Drawing.Imaging.ImageFormat.Jpeg : System.Drawing.Imaging.ImageFormat.Png;
}
private void btn_reset_Click(object sender, EventArgs e)
{
ResetFields();
}
private void ResetFields()
{
txt_QR.Text = string.Empty;
txt_dimension.Value = 200;
txt_margin.Value = 0;
bgColor = Color.White;
color = Color.Black;
txt_selected_color.BackColor = bgColor;
txt_selected_bgcolor.BackColor = color;
logoBmp = null;
selected_logo.Image = null;
pictureBox.Image = null;
}
private static void ShowError(string title, string message)
{
MessageBox.Show($"{title}: {message}", "Error");
}
}
}Imports IronQr
Imports IronSoftware.Drawing
Imports Color = IronSoftware.Drawing.Color
Namespace IronQR_QR_Generator_WinForms
Partial Public Class QR_Generator
Inherits Form
Private qrCodesDirectory As String = System.IO.Path.Combine(Application.StartupPath, "QR Codes")
Private bgColor As Color = Color.White
Private color As Color = Color.Black
Private logoBmp? As AnyBitmap = Nothing
Public Sub New()
InitializeComponent()
SetLicenseKey()
EnsureDirectoryExists(qrCodesDirectory)
End Sub
Private Shared Sub SetLicenseKey()
IronQr.License.LicenseKey = "License-Key"
End Sub
Private Shared Sub EnsureDirectoryExists(ByVal path As String)
If Not System.IO.Directory.Exists(path) Then
System.IO.Directory.CreateDirectory(path)
End If
End Sub
Private Sub btn_color_Click(ByVal sender As Object, ByVal e As EventArgs)
UpdateColor(color, txt_selected_color, False)
End Sub
Private Sub btn_background_Click(ByVal sender As Object, ByVal e As EventArgs)
UpdateColor(bgColor, txt_selected_bgcolor, True)
End Sub
Private Function ColorToHex(ByVal color As System.Drawing.Color) As String
Return $"#{color.R:X2}{color.G:X2}{color.B:X2}"
End Function
Private Sub UpdateColor(ByRef targetColor As Color, ByVal display As Control, ByVal isBackground As Boolean)
If select_color.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
Dim hexColor = ColorToHex(select_color.Color)
targetColor = New Color(hexColor)
display.BackColor = select_color.Color
End If
End Sub
Private Sub btn_logo_Click(ByVal sender As Object, ByVal e As EventArgs)
If select_logo.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
Try
logoBmp = New AnyBitmap(select_logo.FileName)
selected_logo.Image = Image.FromFile(select_logo.FileName)
Catch ex As Exception
ShowError("An error occurred while loading the logo", ex.Message)
End Try
End If
End Sub
Private Sub btn_generate_Click(ByVal sender As Object, ByVal e As EventArgs)
GenerateQRCode()
End Sub
Private Sub GenerateQRCode()
Try
Dim options = New QrOptions(QrErrorCorrectionLevel.High)
Dim myQr = QrWriter.Write(txt_QR.Text, options)
Dim style = CreateStyleOptions()
Dim qrImage = myQr.Save(style)
Dim fileName = $"{DateTime.Now:yyyyMMddHHmmssfff}_QR.png"
Dim fullPath = System.IO.Path.Combine(qrCodesDirectory, fileName)
qrImage.SaveAs(fullPath)
pictureBox.Image = Image.FromFile(fullPath)
Catch ex As Exception
ShowError("An error occurred during QR code generation or saving", ex.Message)
End Try
End Sub
Private Function CreateStyleOptions() As QrStyleOptions
'INSTANT VB TODO TASK: Throw expressions are not converted by Instant VB:
'ORIGINAL LINE: return new QrStyleOptions { BackgroundColor = bgColor, Color = color, Dimensions = txt_dimension.Value > 0 ? Convert.ToInt32(txt_dimension.Value) : throw new ArgumentException("Please select valid dimensions!"), Margins = Convert.ToInt32(txt_margin.Value), Logo = logoBmp != null ? new QrLogo { Bitmap = logoBmp, Width = 50, Height = 50, CornerRadius = 5 } : null };
Return New QrStyleOptions With {
.BackgroundColor = bgColor,
.Color = color,
.Dimensions = If(txt_dimension.Value > 0, Convert.ToInt32(txt_dimension.Value), throw New ArgumentException("Please select valid dimensions!")),
.Margins = Convert.ToInt32(txt_margin.Value),
.Logo = If(logoBmp IsNot Nothing, New QrLogo With {
.Bitmap = logoBmp,
.Width = 50,
.Height = 50,
.CornerRadius = 5
}, Nothing)
}
End Function
Private Sub btn_save_Click(ByVal sender As Object, ByVal e As EventArgs)
SaveQRCode()
End Sub
Private Sub SaveQRCode()
If pictureBox.Image Is Nothing Then
MessageBox.Show("There is no QR code to save.", "Error")
Return
End If
saveFileDialog.Filter = "PNG Files|*.png|JPEG Files|*.jpg"
saveFileDialog.Title = "Save QR Code"
saveFileDialog.FileName = "QRCode"
If saveFileDialog.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
Try
pictureBox.Image.Save(saveFileDialog.FileName, DetermineImageFormat(saveFileDialog.FileName))
MessageBox.Show("QR Code has been saved!", "Success")
Catch ex As Exception
ShowError("An error occurred while saving the QR code", ex.Message)
End Try
End If
End Sub
Private Function DetermineImageFormat(ByVal filePath As String) As System.Drawing.Imaging.ImageFormat
Return If(System.IO.Path.GetExtension(filePath).ToLower() = ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg, System.Drawing.Imaging.ImageFormat.Png)
End Function
Private Sub btn_reset_Click(ByVal sender As Object, ByVal e As EventArgs)
ResetFields()
End Sub
Private Sub ResetFields()
txt_QR.Text = String.Empty
txt_dimension.Value = 200
txt_margin.Value = 0
bgColor = Color.White
color = Color.Black
txt_selected_color.BackColor = bgColor
txt_selected_bgcolor.BackColor = color
logoBmp = Nothing
selected_logo.Image = Nothing
pictureBox.Image = Nothing
End Sub
Private Shared Sub ShowError(ByVal title As String, ByVal message As String)
MessageBox.Show($"{title}: {message}", "Error")
End Sub
End Class
End NamespaceImports IronQr
Imports IronSoftware.Drawing
Imports Color = IronSoftware.Drawing.Color
Namespace IronQR_QR_Generator_WinForms
Partial Public Class QR_Generator
Inherits Form
Private qrCodesDirectory As String = System.IO.Path.Combine(Application.StartupPath, "QR Codes")
Private bgColor As Color = Color.White
Private color As Color = Color.Black
Private logoBmp? As AnyBitmap = Nothing
Public Sub New()
InitializeComponent()
SetLicenseKey()
EnsureDirectoryExists(qrCodesDirectory)
End Sub
Private Shared Sub SetLicenseKey()
IronQr.License.LicenseKey = "License-Key"
End Sub
Private Shared Sub EnsureDirectoryExists(ByVal path As String)
If Not System.IO.Directory.Exists(path) Then
System.IO.Directory.CreateDirectory(path)
End If
End Sub
Private Sub btn_color_Click(ByVal sender As Object, ByVal e As EventArgs)
UpdateColor(color, txt_selected_color, False)
End Sub
Private Sub btn_background_Click(ByVal sender As Object, ByVal e As EventArgs)
UpdateColor(bgColor, txt_selected_bgcolor, True)
End Sub
Private Function ColorToHex(ByVal color As System.Drawing.Color) As String
Return $"#{color.R:X2}{color.G:X2}{color.B:X2}"
End Function
Private Sub UpdateColor(ByRef targetColor As Color, ByVal display As Control, ByVal isBackground As Boolean)
If select_color.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
Dim hexColor = ColorToHex(select_color.Color)
targetColor = New Color(hexColor)
display.BackColor = select_color.Color
End If
End Sub
Private Sub btn_logo_Click(ByVal sender As Object, ByVal e As EventArgs)
If select_logo.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
Try
logoBmp = New AnyBitmap(select_logo.FileName)
selected_logo.Image = Image.FromFile(select_logo.FileName)
Catch ex As Exception
ShowError("An error occurred while loading the logo", ex.Message)
End Try
End If
End Sub
Private Sub btn_generate_Click(ByVal sender As Object, ByVal e As EventArgs)
GenerateQRCode()
End Sub
Private Sub GenerateQRCode()
Try
Dim options = New QrOptions(QrErrorCorrectionLevel.High)
Dim myQr = QrWriter.Write(txt_QR.Text, options)
Dim style = CreateStyleOptions()
Dim qrImage = myQr.Save(style)
Dim fileName = $"{DateTime.Now:yyyyMMddHHmmssfff}_QR.png"
Dim fullPath = System.IO.Path.Combine(qrCodesDirectory, fileName)
qrImage.SaveAs(fullPath)
pictureBox.Image = Image.FromFile(fullPath)
Catch ex As Exception
ShowError("An error occurred during QR code generation or saving", ex.Message)
End Try
End Sub
Private Function CreateStyleOptions() As QrStyleOptions
'INSTANT VB TODO TASK: Throw expressions are not converted by Instant VB:
'ORIGINAL LINE: return new QrStyleOptions { BackgroundColor = bgColor, Color = color, Dimensions = txt_dimension.Value > 0 ? Convert.ToInt32(txt_dimension.Value) : throw new ArgumentException("Please select valid dimensions!"), Margins = Convert.ToInt32(txt_margin.Value), Logo = logoBmp != null ? new QrLogo { Bitmap = logoBmp, Width = 50, Height = 50, CornerRadius = 5 } : null };
Return New QrStyleOptions With {
.BackgroundColor = bgColor,
.Color = color,
.Dimensions = If(txt_dimension.Value > 0, Convert.ToInt32(txt_dimension.Value), throw New ArgumentException("Please select valid dimensions!")),
.Margins = Convert.ToInt32(txt_margin.Value),
.Logo = If(logoBmp IsNot Nothing, New QrLogo With {
.Bitmap = logoBmp,
.Width = 50,
.Height = 50,
.CornerRadius = 5
}, Nothing)
}
End Function
Private Sub btn_save_Click(ByVal sender As Object, ByVal e As EventArgs)
SaveQRCode()
End Sub
Private Sub SaveQRCode()
If pictureBox.Image Is Nothing Then
MessageBox.Show("There is no QR code to save.", "Error")
Return
End If
saveFileDialog.Filter = "PNG Files|*.png|JPEG Files|*.jpg"
saveFileDialog.Title = "Save QR Code"
saveFileDialog.FileName = "QRCode"
If saveFileDialog.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
Try
pictureBox.Image.Save(saveFileDialog.FileName, DetermineImageFormat(saveFileDialog.FileName))
MessageBox.Show("QR Code has been saved!", "Success")
Catch ex As Exception
ShowError("An error occurred while saving the QR code", ex.Message)
End Try
End If
End Sub
Private Function DetermineImageFormat(ByVal filePath As String) As System.Drawing.Imaging.ImageFormat
Return If(System.IO.Path.GetExtension(filePath).ToLower() = ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg, System.Drawing.Imaging.ImageFormat.Png)
End Function
Private Sub btn_reset_Click(ByVal sender As Object, ByVal e As EventArgs)
ResetFields()
End Sub
Private Sub ResetFields()
txt_QR.Text = String.Empty
txt_dimension.Value = 200
txt_margin.Value = 0
bgColor = Color.White
color = Color.Black
txt_selected_color.BackColor = bgColor
txt_selected_bgcolor.BackColor = color
logoBmp = Nothing
selected_logo.Image = Nothing
pictureBox.Image = Nothing
End Sub
Private Shared Sub ShowError(ByVal title As String, ByVal message As String)
MessageBox.Show($"{title}: {message}", "Error")
End Sub
End Class
End Namespace5단계: 애플리케이션 실행
애플리케이션이 실행되면 입력, 스타일링, 출력 및 작업 섹션으로 구성된 메인 창이 나타납니다. 사용자 인터페이스에 따라 데이터를 입력하고, QR 코드를 맞춤 설정하고, 원하는 대로 QR 코드를 생성 및 저장하세요.
결론
결론적으로, 이 가이드에서는 C# 애플리케이션에서 IronQR 라이브러리를 사용하여 QR 코드를 생성하는 과정을 안내했습니다. Visual Studio에서 프로젝트를 설정하는 것부터 IronQR 라이브러리를 통합하고, 사용자 친화적인 인터페이스를 디자인하고, 백엔드 로직을 작성하는 단계까지 차근차근 설명함으로써, 애플리케이션에 QR 코드 기능을 추가하는 것이 얼마나 쉬운지 보여드렸습니다.
IronQR의 기능을 더 살펴보려면 으로 시작할 수 있습니다. IronQR을 프로젝트에 통합하려는 경우 라이선스 가격은 $999부터 시작하며, 전문가 수준의 QR 코드 생성을 위한 비용 효율적인 솔루션을 제공합니다.
자주 묻는 질문
IronQR란?
IronQR는 Iron Software의 .NET QR 코드 라이브러리입니다. QR 코드 기능을 .NET 응용 프로그램에 통합하고, 다양한 .NET 버전을 지원하며, QR 코드 읽기, 생성 및 커스터마이즈와 같은 기능을 제공합니다.
C# 프로젝트에 IronQR를 어떻게 설치하나요?
NuGet 패키지 관리자를 통해 'IronQR'을 검색하고 설치를 클릭하는 방식으로 또는 NuGet 패키지 관리자 콘솔에서 'Install-Package IronQR'를 입력하여 IronQR를 설치할 수 있습니다.
IronQR를 사용하여 C#에서 QR 코드 생성기를 만드는 단계는 무엇인가요?
QR 코드 생성기를 만들려면 Visual Studio에서 Windows Forms 응용 프로그램을 시작으로 IronQR를 설치하고, UI를 디자인하고, QR 코드 생성 로직을 작성한 다음, 응용 프로그램을 실행하여 QR 코드를 생성합니다.
IronQR로 생성된 QR 코드를 커스터마이즈할 수 있나요?
네, IronQR는 QR 코드의 디자인을 개인화하기 위해 크기, 여백, 색상 및 로고를 추가하는 것과 같은 특정 파라미터들을 설정하여 QR 코드를 커스터마이즈할 수 있도록 합니다.
IronQR에서 라이선스 키의 역할은 무엇인가요?
라이선스 키는 IronQR 라이브러리의 기능을 활성화하기 위해 필요합니다. QR 코드 생성 및 읽기의 전체 기능을 사용하려면 애플리케이션 코드에 라이선스 키를 설정하세요.
IronQR에서 사용할 수 있는 다양한 스캔 모드는 무엇인가요?
IronQR은 손상되거나 읽기 어려운 코드를 포함한 다양한 QR 코드 조건을 다루기 위해 속도와 정확성을 균형 있게 조절하는 혼합 스캔 모드, 머신 러닝 스캔 모드, 기본 스캔 모드를 제공합니다.
IronQR는 QR 코드 읽기를 어떻게 처리하나요?
IronQR는 이미지를 로드하고, 탐지를 위해 준비하며, QrReader를 사용하여 효과적으로 데이터를 분석하고 추출하는 간단한 방법으로 QR 코드를 읽을 수 있게 해줍니다.
IronQR는 다양한 개발 환경과 호환되나요?
네, IronQR는 다양한 .NET 프로젝트 유형을 지원하며, Windows, Linux, macOS, iOS 및 Android와 같은 다양한 환경과 호환됩니다.
IronQR를 사용할 때 오류를 처리하는 권장 방법은 무엇인가요?
QR 코드 생성이나 읽기 중 발생할 수 있는 예외를 캐치하기 위해 애플리케이션에서 오류 처리를 구현하는 것이 원활한 경험을 보장하는 데 권장됩니다.
다른 플랫폼에서 QR 코드 생성기 애플리케이션을 실행할 수 있나요?
네, IronQR의 다양한 .NET Framework와의 호환성을 통해 Windows, Linux 및 macOS와 같은 여러 플랫폼에서 QR 코드 생성기 애플리케이션을 실행할 수 있습니다.
커티스 차우는 칼턴 대학교에서 컴퓨터 과학 학사 학위를 취득했으며, Node.js, TypeScript, JavaScript, React를 전문으로 하는 프론트엔드 개발자입니다. 직관적이고 미적으로 뛰어난 사용자 인터페이스를 만드는 데 열정을 가진 그는 최신 프레임워크를 활용하고, 잘 구성되고 시각적으로 매력적인 매뉴얼을 제작하는 것을 즐깁니다.