ZXing.DelphiでQRコードやCode39バーコードを読む(VCL) ~Delphiソースコード集
ZXing.Delphi(https://github.com/Spelt/ZXing.Delphi)を使うと画像から
QRコードやCode39バーコードなどの画像をスキャンして文字に変換することができます。
ZXing.Delphiダウンロード
https://github.com/Spelt/ZXing.Delphi
から「Code」⇒「Download Zip」をクリックして「ZXing.Delphi-v_3.0.zip」ファイルをダウンロードします。
ダウンロードしたファイルを解凍しておきます。
プロジェクト作成
Delphi IDEを起動したら[ファイル]⇒[新規作成]⇒[VCL フォームアプリケーション -Delphi]をクリックして新規プロジェクトを作成します。
すべて保存ボタンを押して、
..\ドキュメント\Enbarcadero\Studio\Projects
に[新しいフォルダー]ボタンを押して「Vcl_ZXing」等のプロジェクト保存用のフォルダを作成します。
プロジェクト保存用フォルダ内にユニット「Unit1.pas」で保存し、プロジェクト「Project1.dproj」で保存します。
「ZXing.Delphi-v_3.0.zip」ファイルを解凍した中にある「Lib」フォルダを
プロジェクトフォルダ「..\ドキュメント\Enbarcadero\Studio\Projects\Vcl_ZXing」にフォルダごとコピーします。
プロジェクトの設定
[プロジェクト]⇒[オプション]をクリックします。
- 左ペインで[ビルド]⇒[Delphi コンパイラ]を選択します
- ターゲットで[全ての構成]を選択します
-
[条件定義]に以下を入力します
FRAMEWORK_VCL
(入れ忘れて一度でもコンパイルしてエラーが出たときは[条件定義]に FRAMEWORK_VCL を入れてから[プロジェクト]⇒[全てのプロジェクトをビルド]をクリックします) -
[検索パス」に以下を入れます
Lib\Classes;Lib\Classes\Common;Lib\Classes\Common\Detector;Lib\Classes\Common\ReedSolomon;Lib\Classes\Filtering;Lib\Classes\1D Barcodes;Lib\Classes\2D Barcodes;Lib\Classes\2D Barcodes\Decoder;Lib\Classes\2D Barcodes\Detector - 追加したら[保存]ボタンをクリックします。
画面設計
フォームにTButtonとTEditとTImageとTOpenDialogをドラッグドロップします。
ソースコード
Button1をダブルクリックしてソースコードを入力します。
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls;
type
TForm1 = class(TForm)
OpenDialog1: TOpenDialog;
Button1: TButton;
Edit1: TEdit;
Image1: TImage;
procedure Button1Click(Sender: TObject);
private
{ Private 宣言 }
public
{ Public 宣言 }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
uses vcl.imaging.pngImage,
vcl.imaging.jpeg,
ZXing.ReadResult,
ZXing.BarCodeFormat,
ZXing.ScanManager;
procedure TForm1.Button1Click(Sender: TObject);
var bmp:TBitmap;
ScanManager:TScanManager;
ReadResult: TReadResult;
begin
if not OpenDialog1.Execute then Exit;
Image1.Picture.LoadFromFile(OpenDialog1.FileName);
bmp:=TBitmap.Create;
try
bmp.Assign(Image1.Picture.Graphic);
ScanManager:=TScanManager.Create(TBarcodeFormat.Auto,nil);
try
ReadResult:=ScanManager.Scan(bmp);
if ReadResult<>nil then
Edit1.Text:='読み取り成功:'+ReadResult.text
else
Edit1.Text:='読み取り失敗';
finally
ScanManager.Free;
end;
finally
bmp.Free;
end;
end;
end.
実行する
アプリケーションをコンパイルして実行します。
Button1をクリックします。
QRコードやCode39バーコードなどが写っている画像ファイルを選択するとスキャンします。
