C#, VB.NetでZXing.Netを利用してバーコードを作成する例。
(1) ZXing.Netをインストール
Visual Studioの[NuGet パッケージ マネージャー]-[NuGet パッケージの管理]でインストールする。
現時点のバージョンは ZXing.Net.0.16.6
(2) C#の例
//作成
private void ZXing_Write()
{
var writer = new ZXing.BarcodeWriter();
//バーコードの種類
writer.Format = ZXing.BarcodeFormat.QR_CODE;
//サイズ
writer.Options.Height = 200;
writer.Options.Width = 200;
//マージン
writer.Options.Margin = 1;
//文字コード
writer.Options.Hints.Add(ZXing.EncodeHintType.CHARACTER_SET, “Shift_JIS”);
//エラー訂正レベル
writer.Options.Hints.Add(ZXing.EncodeHintType.ERROR_CORRECTION, ZXing.QrCode.Internal.ErrorCorrectionLevel.L);
//作成
pictureBox1.Image = writer.Write(“あいうえお”);
}
//読取
private void ZXing_Read()
{
var img = new Bitmap(pictureBox1.Image);
var reader = new ZXing.BarcodeReader();
//90度ずつ回転させて読取
//reader.AutoRotate = true;
//読み取れなかったときに白黒反転。デコードが遅くなるので注意。
//reader.TryInverted = true;
//数字無しの白黒バーコードの場合
//reader.Options.PureBarcode = true;
//ビットマップをよりDeepに解析
//reader.Options.TryHarder = true;
//文字数制限
//var len1 = new int[] { 10 };
//reader.Options.AllowedLengths = len1;
//コードの種類を限定。複数指定可能。
var BarcodeFormat1 = new List();
BarcodeFormat1.Add(ZXing.BarcodeFormat.QR_CODE); //QR_CODEに限定
reader.Options.PossibleFormats = BarcodeFormat1;
//読取
var result = reader.Decode(img);
if (result != null)
{
label1.Text = result.BarcodeFormat.ToString();
label2.Text = result.Text;
}
img.Dispose();
}
(3) VB.Netの例
‘作成
Private Sub ZXing_Write()
Dim writer As New ZXing.BarcodeWriter
‘バーコードの種類
writer.Format = ZXing.BarcodeFormat.QR_CODE
‘サイズ
writer.Options.Height = 200
writer.Options.Width = 200
‘マージン
writer.Options.Margin = 1
‘文字コード
writer.Options.Hints(ZXing.EncodeHintType.CHARACTER_SET) = “Shift_JIS”
‘エラー訂正レベル
writer.Options.Hints(ZXing.EncodeHintType.ERROR_CORRECTION) = ZXing.QrCode.Internal.ErrorCorrectionLevel.L
‘作成
PictureBox1.Image = writer.Write(“あいうえお”)
End Sub
‘読取
Private Sub ZXing_Read()
Dim img = New Bitmap(PictureBox1.Image)
Dim reader = New ZXing.BarcodeReader()
”90度ずつ回転させて読取
‘reader.AutoRotate = True
”読み取れなかったときに白黒反転。デコードが遅くなるので注意。
‘reader.TryInverted = True
”数字無しの白黒バーコードの場合
‘reader.Options.PureBarcode = True
”ビットマップをよりDeepに解析
‘reader.Options.TryHarder = True
”文字数制限
‘Dim len1() As Integer = {10}
‘reader.Options.AllowedLengths = len1
‘コードの種類を限定。複数指定可能。
Dim BarcodeFormat1 As New List(Of ZXing.BarcodeFormat)
BarcodeFormat1.Add(ZXing.BarcodeFormat.QR_CODE) ‘QR_CODEに限定
reader.Options.PossibleFormats = BarcodeFormat1
‘読取
Dim result As ZXing.Result = reader.Decode(img)
If (result IsNot Nothing) Then
Label1.Text = result.BarcodeFormat.ToString
Label2.Text = result.Text
End If
img.Dispose()
End Sub
2021(令和3)年2月20日 NuGetからインストールできるようになったので記事を書き直し。C#のコードを追加。