C#でQRコードジェネレーターアプリケーションを作成する方法
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コードをスキャンに使用します:

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

処理は、必要な名前空間である IronQr および IronSoftware.Drawing を組み込むことから始まります。特に、画像操作を処理するために、IronSoftware.Drawing 名前空間から Color が言及されます。
QRコード読み取りプロセスに入る前に、ライセンスキーをIronQr.License.LicenseKeyに割り当ててソフトウェアをアクティベートすることが不可欠です。 コードは次に、AnyBitmap.FromFile("QRCode.png") を使用してファイルから QR コード画像を読み込みます。
画像がロードされたら、次にQRコード検出の準備をします。 この準備は、画像のコンテナとして機能する QrImageInput オブジェクトを作成することによって行われます。
この機能の中核は、インスタンス化されてQRコード読み取り操作を実行するために使用されるQrReaderクラスにあります。 リーダーは、準備された画像 qrInput を分析し、含まれている QR コードを検索します。 この操作の結果、QrResult オブジェクトの集合が生成されます。各オブジェクトは、画像内で検出された QR コードを表しています。
QRコードにエンコードされたデータにアクセスして利用するために、コードはループを使用して結果のコレクションを反復処理します。各オブジェクトには、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コードを使用します:

各 QrResult オブジェクトは、デコードされたデータ (Value)、埋め込まれた URL (Url)、および画像内の 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 を含めることから始まります。 カスタムクラス Color は、QR コード生成における色管理を容易にするために定義されており、デフォルトの System.Drawing.Color をオーバーライドして IronQR の要件との互換性を確保します。
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 クラスのコンストラクタは、アプリケーションを使用できるように準備する上で重要な役割を果たします。
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 メソッドによって実現されます。 "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 を使用して、指定されたパスにあるディレクトリが存在するかどうかを確認します。 ディレクトリが存在しない場合(false が返された場合)、Directory.CreateDirectory を使用してディレクトリを作成します。
QRコードディレクトリへのパスは、QR_Generator クラスコンストラクタで qrCodesDirectory として定義されており、アプリケーションの起動パスと"QRコード"フォルダ名が組み合わされています。
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 カラー選択
このアプリケーションは、ユーザーインターフェース上に2つのボタンを提供し、それぞれが色を選択する方法に関連付けられています。btn_color_Click はQRコードの色、btn_background_Click は背景色です。 これらのメソッドは、ユーザーが色を選択できるようにするためにカラーダイアログボックスを活用します。
カラーダイアログボックスを使用して色が選択されると、選択した色は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
UpdateColor メソッドは、選択された色を受け取り、16 進数文字列を使用して IronSoftware.Drawing.Color 形式に変換し、選択に応じて QR コードの前景色または背景色を更新します。
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
画像を正常に選択すると、アプリケーションはそれをロードし、プレビューを表示しようとします。 AnyBitmap オブジェクト、logoBmp には、選択された画像が設定され、これは後で QR 生成ロジックで使用されます。
4.6 QRコードの生成
生成プロセスは、ユーザーが 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 コードの損傷や隠蔽に対する耐性を向上させます。 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 Function
このメソッドは、QrStyleOptions オブジェクトを作成します。このオブジェクトは、QR コード生成ロジックによって使用され、ユーザーの設定が適用されます。 オプションには以下が含まれます:
BackgroundColorおよびColor:これらのプロパティは、QR コードの背景色と前景色を設定し、ブランドや美的嗜好に合わせたパーソナライズされた外観を実現します。Dimensions:このプロパティは QR コードのサイズを決定し、さまざまなコンテキストや媒体内で 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をプロジェクトに統合することを決定した場合、ライセンスは$799から始まり、プロ仕様の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コードを生成し、提供されているオプションを使用して希望の形式で保存します。



