How to Create a QR Code Generator Application In C#
C#を使用してQRコードを作成するためのガイドへようこそ! QRコードと.NETバーコードDLLは、情報を迅速かつ効率的に共有するための人気のある手段になっています。 アプリを開発する場合でも、ウェブサイトを管理する場合でも、リンクを共有するためのきちんとした方法を探している場合でも、これらのコードは非常に便利です。 このガイドでは、 IronQRを使用して QR コードを効率的に生成し、ニーズに合わせた QR コードを生成できるようにする方法を説明します。 このライブラリを使用すると、複雑なロジックに入り込むことなく、C#を使用してQRコードを作成することができます。 手順を案内し、始めるために必要なすべてのものを用意します。 アプリにQRコード生成機能を追加したい場合でも、その方法に興味がある場合でも、正しい場所にいます。 始めましょう。
C#でQRコードジェネレーターを作成する方法
- Visual StudioでWindowsフォームアプリケーションを作成
- NuGetを使用してQRライブラリをインストール
- フォームのフロントエンド要素を設計
- QR生成のロジックを記述
- アプリケーションを実行し、QRコードの作成を開始
IronQR: C# QRライブラリ
IronQRは、.NETアプリケーションにQRコード機能を統合するためのC# QRコードライブラリです。 IronQRは、C#、VB.NET、F#、.NET Core、.NET Standard、.NET Frameworkなど、さまざまな.NETバージョンとプロジェクトタイプをサポートしており、Windows、Linux、macOS、iOS、Androidなどのさまざまな開発環境との互換性を確保します。
IronQRは、QRコードを読み取る能力や生成する能力、複数の画像フォーマットのサポート、QRコードのリサイズ、スタイリング、ロゴの追加などのカスタマイズオプションなどの高度な機能で際立っています。
IronQRの主な機能
IronQRは、基本的なQRコード生成を超え、幅広いQRコード関連のタスクに対応するためのいくつかの機能を提供します。 これらの機能を見て、それらの例コードを確認しましょう。これらは、コンソールアプリなど for .NETアプリケーションテンプレートに簡単に統合できます。
QRコードの読み取り
IronQRはQRコードのデコードに優れており、ユーザーがQRコードに埋め込まれた情報に簡単にアクセスする方法を提供します。 単純なURLから複雑な埋め込まれた情報まで、QRコードからデータを迅速かつ正確に抽出できます。
using IronQr;
using IronSoftware.Drawing;
using Color = IronSoftware.Drawing.Color;
// Set the license key for IronQR
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);
// Print the value of each QR code found in the image
foreach (var result in qrResults)
{
Console.WriteLine(result.Value);
}
using IronQr;
using IronSoftware.Drawing;
using Color = IronSoftware.Drawing.Color;
// Set the license key for IronQR
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);
// Print the value of each QR code found in the image
foreach (var result in qrResults)
{
Console.WriteLine(result.Value);
}
Imports IronQr
Imports IronSoftware.Drawing
Imports Color = IronSoftware.Drawing.Color
' Set the license key for IronQR
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)
' Print the value of each QR code found in the image
For Each result In qrResults
Console.WriteLine(result.Value)
Next result
以下のQRコードをスキャンに使用します:

そして、この出力が得られました:

このプロセスは、必要な名前空間IronSoftware.Drawing名前空間から具体的に言及しています。
QRコード読み取りプロセスに進む前に、ソフトウェアをライセンスキーで有効化し、IronQr.License.LicenseKeyに割り当てることが重要です。 その後、コードはファイルからQRコード画像をAnyBitmap.FromFile("QRCode.png")を使用して読み込みます。
画像がロードされたら、次にQRコード検出の準備をします。 この準備は、画像のコンテナとして機能するQrImageInputオブジェクトを作成することによって行われます。
この機能の核は、QRコード読み取り操作を実行するためにインスタンス化されるQrReaderクラスにあります。 リーダーは、準備された画像qrInputを分析し、それに含まれるQRコードを探します。 この操作の結果は、画像内に検出されたQRコードそれぞれを表すQrResultオブジェクトのコレクションです。
QRコードにエンコードされたデータにアクセスして利用するために、コードはQrResultオブジェクトには、QRコードの値などのプロパティが含まれ、アクセスして表示できます。
カスタムQR読み取りモードオプション
IronQRは画像からQRコードを読み取るさまざまな方法を提供しており、さまざまなニーズに対応可能です。 1つのオプションはミックススキャンモードであり、QRコードが不明瞭であるか一部が隠れているときに役立ちます。
もう1つは機械学習(ML)スキャンモードであり、壊れたり通常の読み取りが難しいQRコードを読むために賢い技術を使用します。 このモードはQRコードの検出が困難な厳しい状況に最適です。
最後に、基本スキャンモードがあり、これは明確でシンプルなQRコードをスキャンするための最も速くシンプルな方法です。 QRコードが読みやすい場合に迅速な結果を得るのに最適です。
using IronQr;
using IronQr.Enum;
using IronSoftware.Drawing;
using Color = IronSoftware.Drawing.Color;
// Set the license key for IronQR
IronQr.License.LicenseKey = "License-Key";
// Load the image file that contains the QR Code
var inputImage = AnyBitmap.FromFile("QRCode.png");
// Using mixed scan mode
QrImageInput mixedScanInput = new QrImageInput(inputImage, QrScanMode.OnlyDetectionModel);
IEnumerable<QrResult> mixedScanResults = new QrReader().Read(mixedScanInput);
// Using machine learning scan mode
QrImageInput mlScanInput = new QrImageInput(inputImage, QrScanMode.OnlyDetectionModel);
IEnumerable<QrResult> mlScanResults = new QrReader().Read(mlScanInput);
// Using basic scan mode
QrImageInput basicScanInput = new QrImageInput(inputImage, QrScanMode.OnlyBasicScan);
IEnumerable<QrResult> basicScanResults = new QrReader().Read(basicScanInput);
using IronQr;
using IronQr.Enum;
using IronSoftware.Drawing;
using Color = IronSoftware.Drawing.Color;
// Set the license key for IronQR
IronQr.License.LicenseKey = "License-Key";
// Load the image file that contains the QR Code
var inputImage = AnyBitmap.FromFile("QRCode.png");
// Using mixed scan mode
QrImageInput mixedScanInput = new QrImageInput(inputImage, QrScanMode.OnlyDetectionModel);
IEnumerable<QrResult> mixedScanResults = new QrReader().Read(mixedScanInput);
// Using machine learning scan mode
QrImageInput mlScanInput = new QrImageInput(inputImage, QrScanMode.OnlyDetectionModel);
IEnumerable<QrResult> mlScanResults = new QrReader().Read(mlScanInput);
// Using basic scan mode
QrImageInput basicScanInput = new QrImageInput(inputImage, QrScanMode.OnlyBasicScan);
IEnumerable<QrResult> basicScanResults = new QrReader().Read(basicScanInput);
Imports IronQr
Imports IronQr.Enum
Imports IronSoftware.Drawing
Imports Color = IronSoftware.Drawing.Color
' Set the license key for IronQR
IronQr.License.LicenseKey = "License-Key"
' Load the image file that contains the QR Code
Dim inputImage = AnyBitmap.FromFile("QRCode.png")
' Using mixed scan mode
Dim mixedScanInput As New QrImageInput(inputImage, QrScanMode.OnlyDetectionModel)
Dim mixedScanResults As IEnumerable(Of QrResult) = (New QrReader()).Read(mixedScanInput)
' Using machine learning scan mode
Dim mlScanInput As New QrImageInput(inputImage, QrScanMode.OnlyDetectionModel)
Dim mlScanResults As IEnumerable(Of QrResult) = (New QrReader()).Read(mlScanInput)
' Using basic scan mode
Dim basicScanInput As New QrImageInput(inputImage, QrScanMode.OnlyBasicScan)
Dim basicScanResults As IEnumerable(Of QrResult) = (New QrReader()).Read(basicScanInput)
高度なQRコードの読み取り
IronQRの高度なQRコード読み取り機能は、QRコードのスキャンとデコードに包括的で細かいアプローチを提供するように設計されています。 この機能セットは基本的なQRコード読み取り機能を超えており、データの抽出と対話を深いレベルで提供します。
using IronQr;
using IronQr.Enum;
using IronSoftware.Drawing;
using Color = IronSoftware.Drawing.Color;
// Set the license key for IronQR
IronQr.License.LicenseKey = "License-Key";
// Load the image to scan
var imageToScan = AnyBitmap.FromFile("QRCode.png");
// Prepare the image for QR code detection
QrImageInput qrInput = new QrImageInput(imageToScan);
// Initialize the QR Code reader
QrReader qrScanner = new QrReader();
// Execute QR Code reading on the provided image
IEnumerable<QrResult> scanResults = qrScanner.Read(qrInput);
// Print the value, URL, and coordinates of each QR code found in the image
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 IronQr.Enum;
using IronSoftware.Drawing;
using Color = IronSoftware.Drawing.Color;
// Set the license key for IronQR
IronQr.License.LicenseKey = "License-Key";
// Load the image to scan
var imageToScan = AnyBitmap.FromFile("QRCode.png");
// Prepare the image for QR code detection
QrImageInput qrInput = new QrImageInput(imageToScan);
// Initialize the QR Code reader
QrReader qrScanner = new QrReader();
// Execute QR Code reading on the provided image
IEnumerable<QrResult> scanResults = qrScanner.Read(qrInput);
// Print the value, URL, and coordinates of each QR code found in the image
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 IronQr.Enum
Imports IronSoftware.Drawing
Imports Color = IronSoftware.Drawing.Color
' Set the license key for IronQR
IronQr.License.LicenseKey = "License-Key"
' Load the image to scan
Dim imageToScan = AnyBitmap.FromFile("QRCode.png")
' Prepare the image for QR code detection
Dim qrInput As New QrImageInput(imageToScan)
' Initialize the QR Code reader
Dim qrScanner As New QrReader()
' Execute QR Code reading on the provided image
Dim scanResults As IEnumerable(Of QrResult) = qrScanner.Read(qrInput)
' Print the value, URL, and coordinates of each QR code found in the image
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 qrResult
IronQRを使用してQRコードをスキャンすると、この出力が得られます:

以下のQRコードを使用します:

各Pointsへのアクセスを提供します。
検出された各QRコードについて、IronQRはQRコード内の正確なコンテンツとすべてのURLを詳細に提供します。 さらに、ライブラリは画像内のQRコードのコーナーの正確な座標を提供します(Pointsプロパティを通じて)。
C#アプリケーションでIronQRライブラリを使用してQRコードジェネレーターを作成するには、これらの手順に従ってください。 このガイドは、Windowsフォームアプリケーションのセットアップ、IronQRライブラリのインストール、QRコードを生成するコードの記述、および出力の理解を案内します。
ステップ1: Visual StudioでWindowsアプリケーションを作成
- コンピューターでVisual Studioを起動します。
- "新しいプロジェクトを作成"ボタンをクリックします。
-
プロジェクトタイプとしてWindowsフォームアプリを選択します。 言語にはC#を選んでください。

-
プロジェクトの名前を入力し、保存する場所を選択します。 次の画面で.NET frameworkを選択します。 作成をクリックします。

これにより、Visual StudioでWindowsフォームアプリケーションが作成され、開きます。
ステップ2: IronQRライブラリをインストール
プロジェクトにIronQRライブラリをインストールする時です。 IronQRライブラリは異なる方法でインストールできます。 お好みの方法を選択してください:
NuGetパッケージマネージャーを使用してインストール
- ソリューションエクスプローラーでプロジェクトを右クリックして、NuGetパッケージの管理を選択します。
-
検索ボックスにIronQRと入力してEnterキーを押します。

-
リストでIronQRを見つけて、横にあるインストールをクリックします。

NuGetパッケージマネージャーコンソールを使用してインストール
- ツール > NuGetパッケージマネージャー > パッケージマネージャーコンソールに進みます。

Install-Package IronQrを入力してEnterを押します。

ステップ3: フロントエンドをデザインする

3.1 タイトルヘッダー

QRコードジェネレーターアプリケーションを起動すると、すぐに"QR Generator IronQR"というタイトルの太くて権威あるフォントによる目立つヘッダーが表示されます。 フォントには、効率性と精度を伝えるクリーンでモダンなラインを持つAgency FBが選ばれています。 48ポイントのフォントサイズで、タイトルは目立ち、自信に満ちており、ユーザーの注意を引き、アプリケーションのアイデンティティをしっかりと確立します。
3.2 入力セクション
QRコード用のテキスト入力

入力セクションの中心には、シンプルかつ基本的なコンポーネントであるテキスト入力ボックスがあります。 ここで、ユーザーはQRコードにエンコードしたいデータを入力できます。 ボックスは広く、多くのテキストを収容し、上部に目立つように配置されています。
ロゴの選択

テキスト入力の下に、"ロゴを選択"領域がカスタマイズの追加レイヤーを可能にします。 ユーザーは、QRコードに埋め込むロゴをアップロードして、ブランド認知を向上させたり、コードを個性化したりすることができます。 隣接するピクチャーボックスは選択されたロゴのプレビューを提供し、即時の視覚的フィードバックを行います。
カラー設定

右側に移動すると、色の選択オプションが表示されます。 QRコードの色用と背景色用の2つのボタンがあり、ユーザーはQRコードのパレットをカスタマイズできます。 これらのボタンの横にあるリッチテキストボックスは、現在選択されている色を表示します。
テキスト、ロゴ、色のオプションを備えた入力セクションの配慮されたレイアウトは、QRコードを作成するときのユーザーの優先順位を明確に理解していることを反映しています。 それは機能性と柔軟性を組み合わせており、ユーザーは必要な情報を迅速かつ効率的に入力することができ、創造性の余地も提供しています。
3.3 スタイルパラメータ

次元の設定
カラーカスタマイズツールに隣接して、"次元"を入力するためのエリアがあります。この数値設定は、QRコードの全体的なサイズを決定し、名刺、フライヤー、デジタルスクリーンなど、意図されたディスプレイのコンテキストにぴったり合うようにします。
余白の設定
次元入力の隣に"余白"フィールドがあり、QRコードの周囲の余白を指定することができます。
余白は単なる美的選択ではなく、スキャナーによるQRコードの読みやすさに影響する機能的要素です。 アプリケーションは、このパラメータを簡単に調整するための数値のアップダウンコントロールを提供します。
3.4 出力プレビュー


これにより、生成されたQRコードのリアルタイムプレビューが提供されます。 この即時の視覚的フィードバックは、ユーザーが設計選択を確認し、保存する前にQRコードが期待通りであることを確認するために重要です。 この即時の視覚的フィードバックは、ユーザーがデザインの選択を確認し、QRコードが保存する前に期待に応えるものであることを確認するために不可欠です。
3.5 アクションボタン
QRを生成

"QRを生成"ボタンは、アプリケーションのインターフェイスにおける重要な制御要素です。 フォーム内に戦略的に配置されたこのボタンは、QRコード生成プロセスの触媒です。 このボタンをクリックすると、アプリケーションはユーザーが定義したすべての入力データとスタイリングパラメータを取得し、カスタムQRコードの生成を開始します。
QRコードを保存

クリックすると保存ダイアログが開き、ユーザーは希望のファイル形式と保存先を選択できます。
フォームをリセット


このボタンを1回クリックするだけで、すべての以前の入力と選択がクリアされ、すべての設定がデフォルト値に復元されます。
ステップ4: バックエンドロジックを書く
4.1 セットアップと初期化
まず、アプリケーションは必要な名前空間IronQrとIronSoftware.Drawingを含めることから始まります。
まず、アプリケーションは必要な名前空間IronSoftware.Drawingを含めることから始まります。 カスタムColorクラスが定義されており、QRコード生成における色管理を容易にし、デフォルトのSystem.Drawing.ColorをオーバーライドしてIronQRの要件と互換性を確保します。 QRコード生成において色管理を促進するカスタムSystem.Drawing.Colorをオーバーライドして定義されます。
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.Color
QR_Generatorクラスのコンストラクターは、アプリケーションを使用するための準備で重要な役割を果たします。 * SetLicenseKey:このメソッドはIronQRライブラリの有効なライセンスキーを適用するために呼び出されます。
public 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
-
SetLicenseKey: このメソッドは、IronQRライブラリに有効なライセンスキーを適用するために呼び出されます。 ライセンスキーの使用は、商業アプリケーションおよびIronQRライブラリの機能を完全に解除するために必須です。 EnsureDirectoryExists: 生成されたQRコードを保存する必要があるため、このメソッドは専用のディレクトリが利用可能であることを保証します。
4.2 ライセンスキーの設定
IronQRが制限なしに操作することを保証するために、有効なライセンスキーを適用する必要があります。
これは、購入済みまたは試用用のライセンスキーをライブラリに設定するように設計された静的メソッドSetLicenseKeyを通じて実現されます。 これは、購入したまたはトライアルライセンスキーでライブラリを設定する静的メソッドSetLicenseKeyによって達成されます。 "YOUR_LICENSE_KEY"をIron Softwareから取得した実際のライセンスキーに置き換えてください。
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 Sub
"YOUR_LICENSE_KEY"をIron Softwareで取得した実際のライセンスキーに置き換えます。 このメソッドはQR_Generatorクラスのコンストラクター内で呼び出され、アプリケーションが起動すると同時に、QRコード生成が始まる前にライセンスが適用されることを保証します。
4.3 ディレクトリ管理
アプリケーションはEnsureDirectoryExistsメソッドを使用して、QRコードを保存するために指定されたディレクトリが存在するかどうかを確認します。 存在しない場合は、ディレクトリを作成します。 このメソッドはstringパラメータを受け取ります。これは確認または作成するディレクトリのパスです。 以下のように実装されています:
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 Sub
このメソッドは、System.IO名前空間を使用してファイルシステムと対話します。 まず、指定されたパスにディレクトリが存在するかどうかをDirectory.Existsを使用してチェックします。 ディレクトリが存在しない場合(Directory.CreateDirectoryを使用してディレクトリを作成します。
QRコードディレクトリのパスは、アプリケーションの起動パスと"QR Codes"フォルダ名を組み合わせたQR_Generatorクラスのコンストラクターで定義されています。
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")
4.4 カラー選択
アプリケーションはQRコードの色選択用のbtn_background_Clickを持つ2つのボタンをユーザーインターフェイスに提供しています。 これらのメソッドは、ユーザーが色を選択できるようにするためにカラーダイアログボックスを活用します。
カラーダイアログボックスを使用して色が選択されると、選択した色は16進数の文字列形式に変換されます。 これは、IronQRライブラリが色を16進数形式で指定する必要があるためです。 変換はColorToHexメソッドを通じて行われます。
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 Function
IronSoftware.Drawing.Color形式に変換し、選択に応じてQRコードの前景または背景色を更新します。 重要なルール:
1. 各項目は番号付きでテキストタグで囲まれています:[N] テキスト
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 Sub
4.5 ロゴの追加
アプリケーションには、ボタン(btn_logo_Click)が含まれており、これをクリックすると、ユーザーがロゴとして使用する画像ファイルを選択できるファイルダイアログが開きます。 この機能は、QRコードのブランディングを行おうとする企業や個人にとって重要です。 ロゴの選択と統合プロセスは次のように処理されます:
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 Sub
画像を正常に選択すると、アプリケーションはそれをロードし、プレビューを表示しようとします。 logoBmpが選択された画像で設定され、その後QR生成ロジックで使用されます。
4.6 QRコードの生成
生成プロセスは、ユーザーが"Generate"ボタンをクリックしたときに開始され、これはbtn_generate_Clickメソッドにリンクされています。 このメソッドはトリガーとして機能し、GenerateQRCode関数を呼び出し、実際の生成ロジックが存在します。
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 Sub
GenerateQRCodeメソッド内で、アプリケーションは入力テキストやスタイルオプションを含む指定されたパラメータに基づいてQRコードを構築します。 CreateStyleOptionsメソッドは、ユーザーのカスタム設定(色、次元、ロゴなどを含む)を含むQrStyleOptionsオブジェクトを生成します。
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 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 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
QrOptionsオブジェクトはエラー訂正レベルを定義し、QRコードの被害または隠蔽に対する耐性を高めます。 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 Function
このメソッドはQrStyleOptionsオブジェクトを作成し、その後QRコード生成ロジックによってユーザーのプリファレンスを適用するのに使用されます。 オプションには以下が含まれます:
Color: これらのプロパティはQRコードの背景と前景色を設定し、ブランドや美的好みに合ったパーソナライズされた外観を提供します。Dimensions: このプロパティはQRコードのサイズを決定し、異なるコンテキストや媒体にどのように適合するかに柔軟性を提供します。Margins: このプロパティはQRコードの周囲の余白サイズを設定し、スケーラビリティにとって重要な隣接要素から隔離します。Logo: ユーザーがロゴを含めることを選択した場合、特定の寸法とポリッシュされた外観のためのコーナー半径でここで構成されます。
4.7 QRコードの保存
保存機能は"節約"ボタンによってトリガーされ、これはbtn_save_Clickメソッドにリンクされています。 このメソッドは保存ロジックを実装するSaveQRCodeを呼び出します。 利用可能な場合、ユーザーはファイルをPNGまたはJPEG形式で保存するオプションを提示されます。
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 Sub
このメソッドは、生成されたQRコードが利用可能かどうかをチェックします。 そうであれば、ユーザーにPNGまたはJPEG形式でファイルを保存するオプションを提示します。 DetermineImageFormat関数は、ユーザーが選択したファイル拡張子に基づいて正しい形式で画像が保存されることを保証します。
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 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 Function
この柔軟性により、ユーザーは品質(PNG)を優先するかファイルサイズ(JPEG)を優先するかに応じて、最適な形式を選択できます。
4.8 アプリケーションのリセット
リセット機能は"リセット"ボタンにリンクされており、これはbtn_reset_Clickメソッドを呼び出します。 このメソッドはさらに、ResetFieldsを呼び出し、これによりすべてのユーザー入力をクリアし、テキストフィールド、色選択、および選択されたロゴを含むすべての設定のデフォルト値を復元するよう設計されています。
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 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 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
このメソッドはQRコード生成に関与する各コンポーネントをリセットします。 アプリケーションは、ShowErrorメソッドを使用して、ユーザーにフレンドリーな方法でエラーメッセージを表示します。
4.9 エラーハンドリング
アプリケーションはShowErrorメソッドを使用して、ユーザーフレンドリーな方法でエラーメッセージを表示します。 このメソッドは、エラーに関する文脈をユーザーに提供するために、タイトルとメッセージの2つのパラメータを取ります。 以下のように実装されています:
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 Sub
このメソッドは、アプリケーションのさまざまな部分で利用されており、エラーが発生した際に、ユーザーに迅速に明確で簡潔なメッセージで通知することを保証します。 例として、ロゴを読み込む際やQRコード生成プロセス時にエラーが発生した場合、アプリケーションは問題の詳細を表示するためにShowErrorを呼び出します。
ステップ5: アプリケーションの実行
アプリケーションが実行されると、提供された画像のようにメインウィンドウが表示されます。
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 Namespace
レイアウトは入力、スタイリング、出力、およびアクションのセクションにきちんと整理されています。
アプリケーションが実行されると、メインウィンドウは提供された画像に示されているように表示されます。 レイアウトは、入力、スタイル、出力、アクションのセクションに neatly organized されています。

プロセスの最初のステップは、"Input QR Text"フィールドにデータを入力することです。 このデータは、URLやテキスト情報など、QRコードの内容を形成します。 次に、QRコードをパーソナライズするために、"Select Logo"ボタンをクリックしてロゴを選択します。 選択後、ロゴはボタンの隣にあるプレビュー ボックスに明示的に配置され、QRコードデザインへの組み込みが確認されます。

ロゴの選択後、QRコードの前景色と背景色を選択します。 それぞれのボタンをクリックすると、選択した色がそのボタンの隣にある色表示ボックスに反映され、即座に選択の視覚的確認ができます。

この特定のQRコードでは、サイズを500に設定し、ニーズに適したサイズになるようにし、マージンを20に調整します。これにより、QRコードの周囲にバッファが提供され、スキャンの問題を防ぎます。

すべての入力とスタイルオプションが設定されたら、"Generate QR"ボタンをクリックしてQRコードを生成します。 アプリケーションは私たちの入力を処理し、出力画像ボックスに新しく作成されたQRコードを表示します。

生成されたQRコードを保存するには、"Save QR"ボタンをクリックするだけです。 このアクションにより、保存ダイアログが開き、QRコード画像の保存先とファイル形式を選択できます。

保存が完了すると、QRコードが正常に保存されたことを確認する成功メッセージが表示されます。

最初からやり直したり、新しい QR コードを作成したりする必要がある場合は、"フォームをリセット"ボタンをクリックすると、フォームが元の状態に戻り、すべてのフィールドと選択がクリアされ、次の QR コード生成の準備が整います。

これはIronQRによって生成された保存済みのQRコードです:

結論
結論として、このガイドはC#アプリケーションでIronQRライブラリを使用してQRコードを生成するプロセスを案内しました。 Visual Studioでプロジェクトをセットアップし、IronQRライブラリを統合し、ユーザーフレンドリーなインターフェースをデザインし、バックエンドロジックを記述する手順を分解することにより、アプリケーションにQRコード機能を追加する方法の簡単さを示しました。
IronQRの機能をさらに探求したい方には、無料試用版が提供されていることを覚えておいてください。 IronQRをプロジェクトに統合しようとする場合、ライセンスは$999から始まり、プロフェッショナルグレードのQRコード生成に対する費用対効果の高いソリューションを提供します。
よくある質問
C#でQRコードジェネレーターアプリケーションを作成するにはどうすればよいですか?
C#でQRコードジェネレーターアプリケーションを作成するには、Visual StudioでWindows フォーム アプリケーションをセットアップすることから始めます。NuGet経由でIronQRライブラリをインストールし、テキスト、ロゴ、および色の入力フィールドを持つインターフェースを設計し、IronQRのメソッドを使用してQRコード生成のロジックを実装します。
C#で利用可能なQRコードのカスタマイズオプションは何ですか?
IronQRは、色、寸法、余白を変更するなどのQRコードのカスタマイズオプションを提供します。QrStyleOptions オブジェクトの設定を調整することで、QRコードにロゴを追加することもできます。
C#プロジェクトにQRコードライブラリをインストールするにはどうすればよいですか?
Visual StudioのNuGetパッケージマネージャーを使用して、C#プロジェクトにIronQRライブラリをインストールします。IronQRを検索して「インストール」ボタンをクリックしてプロジェクトに追加します。
生成されたQRコードをC#で保存するために使用できる形式は何ですか?
IronQRを使用すると、生成したQRコードをPNGやJPEGなどのさまざまな形式で保存でき、品質やファイルサイズの観点から柔軟性を提供します。
C#ライブラリを使用してQRコードを読み取ることができますか?
はい、IronQRはQRコードを読み取る機能を含んでおり、QR画像からデータを効果的にデコードおよび抽出できます。
C# QRコードライブラリを使用する利点は何ですか?
IronQRのようなC# QRコードライブラリはQRコードの生成と読み込みのプロセスを簡略化し、多形式サポート、カスタマイズオプション、さまざまな.NETバージョンとの互換性などの機能を提供します。
C#でQRコードを生成する際にエラーを処理する方法は?
C#でtry-catchブロックを使用することで、QRコード生成アプリケーションにエラー処理を組み込むことができます。これにより、QRコードの作成中に発生する問題をスムーズに管理し、ユーザーフレンドリーなフィードバックを提供します。
C#アプリケーションでQRコードライブラリを使用するにはライセンスが必要ですか?
はい、IronQRを制限なく使用するには、有効なライセンスキーが必要です。初期テスト用の試用版が利用可能で、完全アクセス用のプロフェッショナルライセンスを購入できます。
C#でQRコードにロゴを統合するにはどうすればよいですか?
IronQRを使用すると、QRコードにロゴ画像をQrStyleOptionsオブジェクトに設定することで統合できます。これにより、QRコードをブランディング要素で個別化できます。
C#でQRコードジェネレーターアプリケーションを実行する手順は何ですか?
C#でQRコードジェネレーターアプリケーションを設定してカスタマイズした後、Visual Studio でアプリケーションを実行し、QRコードを生成し、提供されているオプションを使用して希望の形式で保存します。




