fc2ブログ

記事一覧

ZXingで画像ファイルの中にあるQRコードを認識してデコードする方法 | Xamarin.Forms


今回は画像の中に表示されているQRコードを認識して文字列を読み取る方法についてご紹介いたします。通常では、印刷されているQR画像をカメラで読み取ってからスキャンしますが、既にカメラで撮られた画像やスナップショットまたはメールで送られてくるファイルなどはスキャンすることができません。
そのような場合にファイルの中のQRコードを認識して読み取ることができれば良いなと思い試してみたところ、ZXingを使用して簡単に実現ができました。





前提条件
・Windows10 Pro 64Bit
・Visual Studio 2015 Community Update3
・Xamarin 4.3.0.795 (NuGet Xamarin.Forms 2.3.4.270)
・macOS Sierra 10.12.4 / Xcode8.3.1 / Xamarin.iOS 10.6.0.10



1.ZXingのインストール

NuGetパッケージマネージャからインストールします。
今回は使用しませんが、カメラ機能に関してはNuGetパッケージに不具合もありますので、以前の記事「ZXing が iOS10 で 動作しないバグを修正する方法」をご確認されると良いでしょう。



2.PCLの記述方法

PCLプロジェクトにDependencySerivceから呼び出せるようにインターフェースを実装します。

IZxingService.cs
namespace AppName.Services
{
    //DependencyServiceから利用する
public interface IZxingService
{
string GetDecodedValue(byte[] image);
}
}



3.Androidの実装方法

Androidプロジェクト内に以下のファイルを記述します。

ZxingService.cs
[assembly: Dependency(typeof(ZxingService))]
namespace AppName.Droid.Services
{
    public class ZxingService : IZxingService
    {
        public string GetDecodedValue(byte[] image)
{
if (image == null || image.Length == 0)
{
return String.Empty;
}

ZXing.Result result = null;

try
{
// オプションでサイズを指定してBitmapオブジェクトを生成
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.InSampleSize = 2;
Bitmap bitmap = BitmapFactory.DecodeByteArray(image, 0, image.Length, opts);

//3次元配列で画像のRGBを取得する
byte[] rgbBytes = ImageService.GetRgbBytes(bitmap);
LuminanceSource source = new RGBLuminanceSource(rgbBytes, bitmap.Width, bitmap.Height);
BinaryBitmap bb = new BinaryBitmap(new HybridBinarizer(source));

//QRコードを読み取り
var reader = new MultiFormatReader();
IDictionary<DecodeHintType, object> hints = new Dictionary<DecodeHintType, object>();
hints.Add(ZXing.DecodeHintType.PURE_BARCODE, true);
//hints.Add(ZXing.DecodeHintType.POSSIBLE_FORMATS, new List<BarcodeFormat>() { BarcodeFormat.QR_CODE }); //無くても動作します。
hints.Add(ZXing.DecodeHintType.TRY_HARDER, true);
reader.Hints = hints;
result = reader.decode(bb);
}
catch (Exception ex)
{
// fall thru, it means there is no QR code in image
}

if (result != null)
{
return result.Text;
}
return String.Empty;
}
    }
}

ImageService.GetRgbBytesメソッドは前回の記事「画像データからピクセル毎のRGB配列を取得する方法」にてご紹介しております。



4.iOSの実装方法

iOSプロジェクト内に以下のファイルを記述します。

ZxingService.cs
using UIKit;
using CoreGraphics;
using ZXing;
using Xamarin.Forms;
[assembly: Dependency(typeof(ZxingService))]
namespace AppName.iOS.Services
{
    public class ZxingService : IZxingService
    {
        public string GetDecodedValue(byte[] image)
{
if (image == null || image.Length == 0)
{
return String.Empty;
}

ZXing.Result result = null;

try
{
//バイト配列からUIImageを取得
var data = NSData.FromArray(image);
var uiimage = UIImage.LoadFromData(data);

//3次元配列で画像のRGBを取得する
byte[] rgbBytes = ImageService.GetRgbBytes(uiimage);
LuminanceSource source = new RGBLuminanceSource(rgbBytes, (int)uiimage.Size.Width, (int)uiimage.Size.Height);
BinaryBitmap bb = new BinaryBitmap(new HybridBinarizer(source));

//QRコードを読み取り
var reader = new MultiFormatReader();
IDictionary<DecodeHintType, object> hints = new Dictionary<DecodeHintType, object>();
hints.Add(ZXing.DecodeHintType.PURE_BARCODE, true);
//hints.Add(ZXing.DecodeHintType.POSSIBLE_FORMATS, new List<BarcodeFormat>() { BarcodeFormat.QR_CODE }); //無くても動作します。
hints.Add(ZXing.DecodeHintType.TRY_HARDER, true);
reader.Hints = hints;
result = reader.decode(bb);
}
catch (Exception ex)
{
// fall thru, it means there is no QR code in image
}

if (result != null)
{
return result.Text;
}
return String.Empty;
}
    }
}

ImageService.GetRgbBytesメソッドは前回の記事「画像データからピクセル毎のRGB配列を取得する方法」にてご紹介しております。



5.使用方法

PCLプロジェクトの中の任意のページに記述します。
ImageコントロールのImageSourceをバイト配列に変換してからDependencyServiceに受け渡します。
バイト配列に変換する方法は以前の記事「ImageSourceからSystem.IO.Streamに変換する方法」「System.IO.Streamをバイト配列(Byte[])に変換する方法」をご確認ください。

TestPage.xaml.cs
using AppName.Services;
using Xamarin.Forms;
public class TestPage : ContentPage
{
void OnScanClick(object sender, EventArgs e)
{
    byte[] byteArray = null;
if (this.imgPicture.Source.GetType() == typeof(StreamImageSource))
{
//ImageSourceからStreamを取得する
Stream stream = ImgConverter.GetStreamFromImageSource(this.imgPicture.Source);
//Streamをバイト配列に変換する
byteArray = ImgConverter.GetByteArrayFromStream(stream);

//画像からQRデータを読み込む
string result = DependencyService.Get<IZxingService>().GetDecodedValue(byteArray);
}
}
}







最後までお読みいただきありがとうございます。
当ブログの内容をまとめた Xamarin逆引きメニュー は以下のURLからご覧になれます。
https://itblog.dynaspo.com/blog-entry-81.html



関連記事

コメント

コメントの投稿

※名前とタイトルが入力されていないコメントでは他のコメントとの区別ができません。

 入力されていないコメントには返信しませんのであらかじめご了承くださいませ。

※ニックネームでも良いので必ずご入力ください。

    

※必ずご入力ください。

    
    

※必ずご入力ください。

※技術的な質問には環境やエラーについて正確かつ詳細にお教えください。

・正確なエラーの内容

・Windowsのバージョン番号

・Visual Studioのバージョン

・機器の型番

・アプリやソフトのバージョン

    

カテゴリ別記事一覧

広告

プロフィール

石河 純


著者名 :石河 純
自己紹介:素人上がりのIT技術者。趣味は卓球・車・ボウリング

IT関連の知識はざっくりとこんな感じです。
【OS関連】
WindowsServer: 2012/2008R2/2003/2000/NT4
Windows: 10/8/7/XP/2000/me/NT4/98
Linux: CentOS RedHatLinux9
Mac: macOS Catalina 10.15 / Mojave 10.14 / High Sierra 10.13 / Sierra 10.12 / OSX Lion 10.7.5 / OSX Snow Leopard 10.6.8
【言語】
VB.net ASP.NET C#.net Java VBA
Xamarin.Forms
【データベース】
Oracle 10g/9i
SQLServer 2016/2008R2/2005/2000
SQLAnywhere 16/11/8
【BI/レポートツール】
Cognos ReportNet (IBM)
Microsoft PowerBI
ActiveReport (GrapeCity)
CrystalReport
【OCX関連】
GrapeCity InputMan SPREAD MultiRow GridView
【ネットワーク関連】
CCNP シスコ技術者認定
Cisco Catalyst シリーズ
Yamaha RTXシリーズ
FireWall関連
【WEB関連】
SEO SEM CSS jQuery IIS6/7 apache2

休みの日は卓球をやっています。
現在、卓球用品通販ショップは休業中です。