In these examples 1D barcodes (Code39 and Code128) are read. To see how to read 2D and postal barcode click here.
Table of contents
- Programming languages code examples
- Shell script invocation examples
- Basic barcode reading from a file
- Read barcodes from Web-based images using URL
- Configure options and sources through configuration file
- Read driver license barcodes
- Read barcodes from multiple files in a folder
- Read barcodes containing text in local languages
- Read barcodes using Targeted Barcode Reader (TBR)
- Use TBR-Wizard to find the best TBR
The complete list of BarcodeReaderCLI command line options is here. To do actual testing install BarcodeReaderCLI executable and test images per instructions.
Programming languages code examples
Basic functionality invoking BarcodeReaderCLI is demonstrated in various programming languages. To test install BarcodeReaderCLI executable and test images per instructions.PHP
12345678910111213141516171819202122232425262728293031323334353637
<?php// php brcli-example.php -> use BarcodeReaderCLI command line // php brcli-example.php config -> use BarcodeReaderCLI configuration file chdir(__DIR__); $args = array('"../bin/BarcodeReaderCLI"','-type=code128','"https://wabr.inliteresearch.com/SampleImages/1d.pdf"',); $configFile = './brcli-example.config';$argsConfig = array('"../bin/BarcodeReaderCLI"','@"' . $configFile . '"',); function doExec($cmd, &$stdout=null, &$stderr=null) { $proc = proc_open($cmd,[ 1 => ['pipe','w'], 2 => ['pipe','w'], ],$pipes); $stdout = stream_get_contents($pipes[1]); fclose($pipes[1]); $stderr = stream_get_contents($pipes[2]); fclose($pipes[2]); return proc_close($proc);} $output = ""; $error = "";$params = implode(" ", $argc > 1 ? $argsConfig : $args);if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') $params = '"' . $params . '"'; doExec($params, $output, $error);if ($output != "") echo "STDOUT:\n $output";if ($error != "") echo "STDERR:\n $error";?>
Node.js
12345678910111213141516171819202122
// node brcli-example.js -> use BarcodeReaderCLI command line // node brcli-example.js config -> use BarcodeReaderCLI configuration file var cp = require('child_process');process.chdir(__dirname); var exe = '../bin/BarcodeReaderCLI';var args = [];args.push('-type=code128');args.push('https://wabr.inliteresearch.com/SampleImages/1d.pdf'); var configFile = "./brcli-example.config";var argsConfig = []; argsConfig.push('@' + configFile); const proc = cp.spawn(exe, process.argv.length > 2 ? argsConfig : args);proc.stdout.on('data', (data) => { console.log(data.toString());});proc.stderr.on('data', (data) => { console.error(data.toString());});
C#
123456789101112131415161718192021222324252627282930313233343536373839404142
// csi brcli-example.csx -> use BarcodeReaderCLI command line// csi brcli-example.csx config -> use BarcodeReaderCLI configuration file e// csi is installed on Windows with Visual Studio in C:\Program Files (x86)\MSBuild\{version}\Bin// csi is installed on Linux with Mono using System;using System.IO;using System.Runtime.CompilerServices; static string thisDirectory([CallerFilePath] string path = "") => Path.GetDirectoryName(path);Directory.SetCurrentDirectory(thisDirectory()); string exe = "../bin/BarcodeReaderCLI";string[] args = {"-type=code128","https://wabr.inliteresearch.com/SampleImages/1d.pdf",}; // Obtain options and sources from a configuration filestring configFile = "./brcli-example.config";string[] argsConfig = {"@\"" + configFile + "\""}; string output;string error; using (Process proc = new Process()){ proc.StartInfo = new ProcessStartInfo { FileName = exe, Arguments = string.Join(" ", (Args.Count > 0) ? argsConfig : args), UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true, }; proc.Start(); error = proc.StandardError.ReadToEnd(); output = proc.StandardOutput.ReadToEnd(); proc.WaitForExit();}; if (output != "") Console.WriteLine("STDOUT:\n" + output);if (error != "") Console.WriteLine("STDERR:\n" + error);
Python
12345678910111213141516171819202122232425262728293031323334
# python brcli-example.py -> use BarcodeReaderCLI command line # python brcli-example.py config -> use BarcodeReaderCLI configuration file # use python 3.5 or newer# python3 brcli-example.py -> use BarcodeReaderCLI command line # python3 brcli-example.py config -> use BarcodeReaderCLI configuration file import subprocessimport osimport sys dir = os.path.dirname(os.path.realpath(__file__))os.chdir(dir) exe = '../bin/BarcodeReaderCLI' args = []args.append(exe)args.append('-type=code128')args.append('https://wabr.inliteresearch.com/SampleImages/1d.pdf') configFile = './brcli-example.config'argsConfig = []argsConfig.append(exe)argsConfig.append('@' + configFile) if len(sys.argv) > 1 : args = argsConfigcp = subprocess.run(args, universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) output=cp.stdouterror=cp.stderr if output != "": print("STDOUT:\n" + output)if error != "": print("STDERR:\n" + error)# print("RETURN CODE:" + str(print(cp.returncode)))
Ruby
123456789101112131415161718192021222324252627282930
# encoding: utf-8# ruby brcli-example.rb -> use BarcodeReaderCLI command line # ruby brcli-example.rb config -> use BarcodeReaderCLI configuration file require 'open3'dir = File.dirname(__FILE__) # enable 'require' use modules in script folderDir.chdir(dir) args = Array['../bin/BarcodeReaderCLI','-type=code128','"https://wabr.inliteresearch.com/SampleImages/1d.pdf"',] configFile = './brcli-example.config'argsConfig = Array['../bin/BarcodeReaderCLI','@"' + configFile + '"'] args = argsConfig if ARGV.length > 0params = args.join(' ')output, error, status = Open3.capture3(params) if output != "" then puts "STDOUT:\n " + outputendif error != "" then puts "STDERR:\n " + errorend
Java
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.File; // javac brcli_example.java -> compile example// java -cp . brcli_example -> use BarcodeReaderCLI command line // java -cp . brcli_example config -> use BarcodeReaderCLI configuration file public class brcli_example{ public static String implode(String separator, String[] data) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < data.length - 1; i++) { //data.length - 1 => to not add separator at the end if (!data[i].matches(" *")) {//empty string are ""; " "; " "; and so on sb.append(data[i]); sb.append(separator); } } sb.append(data[data.length - 1].trim()); return sb.toString(); } public static void main(String []args) throws IOException { boolean isWindows = System.getProperty("os.name").toLowerCase().startsWith("windows"); File myDir = new File(brcli_example.class.getProtectionDomain().getCodeSource().getLocation().getPath()); String exe; if (isWindows) exe = "..\\bin\\BarcodeReaderCLI"; else exe = "../bin/BarcodeReaderCLI"; String[] cargs = { exe, "-type=code128", "https://wabr.inliteresearch.com/SampleImages/1d.pdf"}; String configFile = "./brcli-example.config"; String[] cargsConfig = { exe, "@" + configFile}; String cmd = implode(" ", args.length > 0 ? cargsConfig : cargs); ProcessBuilder builder = new ProcessBuilder(); if (isWindows) { builder.command("cmd.exe", "/c", cmd); } else { builder.command("sh", "-c", cmd); } builder.directory(myDir); builder.redirectErrorStream(true); Process process = builder.start(); try (BufferedReader reader = new BufferedReader( new InputStreamReader(process.getInputStream()))) { String line; while ((line = reader.readLine()) != null) { System.out.println(line); } } }}
C++
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
// Your First C++ Program // g++ -o _example brcli-example.cpp -> compile example// _example -> use BarcodeReaderCLI command line // _example config -> use BarcodeReaderCLI configuration file // On Linux use ./_example #include <iostream>#include <string>#include <memory> std::string exec(const char* cmd) { std::array<char, 128> buffer; std::string result; std::unique_ptr<FILE, decltype(&pclose)> pipe(popen(cmd, "r"), pclose); if (!pipe) { return "popen() failed!"; } while (fgets(buffer.data(), buffer.size(), pipe.get()) != nullptr) { result += buffer.data(); } return result;} int main(int argc, char *argv[]) {#if defined _WIN32 || defined _WIN64 std::string exe = "..\\bin\\BarcodeReaderCLI";#else std::string exe = "../bin/BarcodeReaderCLI";#endif std::string cmd = ""; if (argc > 1) { std::string configFile = "./brcli-example.config"; std::string cargsConfig[] = { exe, "@" + configFile}; for (int i = 0; i < sizeof(cargsConfig)/sizeof(cargsConfig[0]); i++) cmd += cargsConfig[i] + " "; } else { std::string cargs[] = { exe, "-type=code128", "https://wabr.inliteresearch.com/SampleImages/1d.pdf"}; for (int i = 0; i < sizeof(cargs)/sizeof(cargs[0]); i++) cmd += cargs[i] + " "; } std::string out = exec(cmd.c_str()); std::cout << out << std::endl; return 0;}
Go
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
package main import ( "os/exec" . "fmt" "runtime" "bytes" "os") // go run brcli-example.go -> use BarcodeReaderCLI command line // go run brcli-example.go config -> use BarcodeReaderCLI configuration file func main() { isWindows := runtime.GOOS == "windows" exe, shell, flag := "../bin/BarcodeReaderCLI", "sh", "-c" if isWindows { exe, shell, flag = "..\\bin\\BarcodeReaderCLI", "cmd.exe", "/c" } args := []string{ exe, "-type=code128", "https://wabr.inliteresearch.com/SampleImages/1d.pdf"} configFile := "./brcli-example.config" argsCongig := []string{ exe, "@" + configFile + ""} cmd := "" if (len(os.Args) > 1){ for _, s := range argsCongig {cmd = cmd + s + " "} } else { for _, s := range args {cmd = cmd + s + " "} } proc := exec.Command(shell, flag, cmd) var stdout bytes.Buffer var stderr bytes.Buffer proc.Stdout = &stdout proc.Stderr = &stderr proc.Run() if stdout.Len() > 0 { Print("STDOUT: \n" + stdout.String())} if stderr.Len() > 0 { Print("STDERR: \n" + stderr.String())}}
Shell script invocation examples
Basic barcode reading from a file
Windows
12345678910111213
@setlocal enableextensions@cd /d "%~dp0"@echo off set EXE=..\bin\BarcodeReaderCLIset OUTDIR=%TEMP%\brcliset INPDIR=.\images REM ===== Read Code39 barcode. Output is default JSON format%EXE% %OPT% %AUTH% -type=code39 "%INPDIR%\test.tif" REM ===== Read Code39 barcode. Output just text value to console%EXE% %OPT% %AUTH% -type=code39 "%INPDIR%\test.tif" -format=text --output-text="{text}"
Linux
1234567891011121314151617
#!/bin/bash HERE="$(dirname "$(readlink -f "${0}")")"cd $HERE EXE=../bin/BarcodeReaderCLIOUTDIR=/tmp/brcliINPDIR=./images # ===== Read Code39 barcode. Output is default JSON format$EXE $OPT $AUTH -type=code39 "$INPDIR/test.tif" # ===== Read Code39 barcode. Output just text value to console$EXE $OPT $AUTH -type=code39 "$INPDIR/test.tif" -format=text --output-text="{text}" # Output new lineecho
Read barcodes from Web-based images using URL
Windows
1234567891011
@setlocal enableextensions@cd /d "%~dp0"@echo off set EXE=..\bin\BarcodeReaderCLIset OUTDIR=%TEMP%\brcliset INPDIR=.\images REM ===== Read barcoded from Web-based images. REM ===== Read multiple images with a single call, applying different 'type' option to each image %EXE% %OPT% %AUTH% -type=pdf417 "https://wabr.inliteresearch.com/SampleImages/drvlic.ca.jpg" -type=code39 "https://www.dropbox.com/s/qcd8zfdvckwwdem/img39.pdf?dl=1"
Linux
123456789101112
#!/bin/bash HERE="$(dirname "$(readlink -f "${0}")")"cd $HERE EXE=../bin/BarcodeReaderCLIOUTDIR=/tmp/brcliINPDIR=./images # ===== Read barcoded from Web-based images. # ===== Read multiple images with a single call, applying different 'type' option to each image $EXE $OPT $AUTH -type=pdf417 "https://wabr.inliteresearch.com/SampleImages/drvlic.ca.jpg" -type=code39 "https://www.dropbox.com/s/qcd8zfdvckwwdem/img39.pdf?dl=1"
Configure options and sources through configuration file
Windows
12345678910
@setlocal enableextensions@cd /d "%~dp0"@echo off set EXE=..\bin\BarcodeReaderCLIset OUTDIR=%TEMP%\brcliset INPDIR=.\images REM ===== Use configuration file%EXE% %OPT% %AUTH% @"brcli-example.config"
Linux
123456789101112
#!/bin/bash HERE="$(dirname "$(readlink -f "${0}")")"cd $HERE EXE=../bin/BarcodeReaderCLIOUTDIR=/tmp/brclirm -rf $OUTDIRINPDIR=./images # ===== Use configuration file to setup complex processing. Demonstrates:$EXE $OPT $AUTH @"brcli-example.config"
Read driver license barcodes
Windows
12345678910
@setlocal enableextensions@cd /d "%~dp0"@echo off set EXE=..\bin\BarcodeReaderCLIset OUTDIR=%TEMP%\brcliset INPDIR=.\images REM ===== Read and decode Driver License%EXE% %OPT% %AUTH% -type=drvlic "%INPDIR%\test.tif"
Linux
The provided URL ('snippets/BarcodeReaderCLI-examples-beta1/linux/driver-licens.sh'), parsed remotely as ('http://snippets/BarcodeReaderCLI-examples-beta1/linux/driver-licens.sh'), could not be accessed.
Read barcodes from multiple files in a folder
Windows
1234567891011121314
@setlocal enableextensions@cd /d "%~dp0"@echo off set EXE=..\bin\BarcodeReaderCLIset OUTDIR=%TEMP%\brcliset INPDIR=.\images REM ===== Read barcode in a folder and sub-folders. Linit file types to BMP and PDF%EXE% %OPT% %AUTH% -type=pdf417 -sub -incl="*.bmp *.pdf" "%INPDIR%\" echo =================== Windows Command windows incorrectly represents UTF-8 textecho Use -output options to get correct UTF-8 textecho Or use Windows Terminal (https://docs.microsoft.com/en-us/windows/terminal/)
Linux
1234567891011
#!/bin/bash HERE="$(dirname "$(readlink -f "${0}")")"cd $HERE EXE=../bin/BarcodeReaderCLIOUTDIR=/tmp/brcliINPDIR=./images # ===== Read barcode in a folder and sub-folders. Linit file types to BMP and PDF$EXE $OPT $AUTH -type=pdf417 -sub -incl="*.bmp *.pdf" "$INPDIR/"
Read barcodes containing text in local languages
Processing is configured in encoding.config file. Output is send to JSON, XML, CSV and TEXT files. TEXT file format is configured in template.txt file.Windows
1234567891011121314151617
@setlocal enableextensions@cd /d "%~dp0"@echo off set EXE=..\bin\BarcodeReaderCLIset OUTDIR=%TEMP%\brcliset INPDIR=.\images REM ===== Use configuration file to setup complex processing. Demonstrates:REM - Reading files with language-specfic file namesREM - Reading language-specfic barcode test valuesREM - Template-based format of TXT output %EXE% %OPT% %AUTH% @"encoding.config" -output=console REM echo =================== Windows console output incorrectly represents UTF-8 textREM echo See output files in %OUTDIR%\utf.*REM echo Or use Windows Terminal (https://docs.microsoft.com/en-us/windows/terminal/)
Linux
123456789101112131415161718192021222324
#!/bin/bash HERE="$(dirname "$(readlink -f "${0}")")"cd $HERE EXE=../bin/BarcodeReaderCLIOUTDIR=/tmp/brclirm -rf $OUTDIRINPDIR=./images # ===== Use configuration file to setup complex processing. Demonstrates:# - Reading files with language-specfic file names# - Reading language-specfic barcode test values# - Template-based format of TXT output # ==== To recognize UTF8 filenames in test/images/encoding folder, system locale should be set to UTF-8# For example starting Docker Ubuntu container call:# RUN apt update && apt-get install -y locales-all# ENV LC_ALL en_US.UTF-8 $EXE $OPT $AUTH -d="OUTDIR=$OUTDIR/" @"encoding.config" -output=console echo Output is written to $OUTDIR folder:ls $OUTDIR
encoding.config
1234567891011121314151617181920212223242526272829303132333435
# ============ OPTIONS-type=pdf417,qr,datamatrix # ============ INPUT-d="SRCDIR=images/encoding/" "{SRCDIR}QR.UTF8.japanese.プライバシーマーク.png" # =========== Read language-encoded barcodes# USE 'encoding' to get UTF8 text-encoding=CP1256"{SRCDIR}DM.CP1256.arabic.بساطة لأنه الأل.tif" -encoding=BIG5"{SRCDIR}PDF417.big5.Chinese.包含一杯准饮料.bmp" -encoding=CP1251"{SRCDIR}PDF417.cp1251.russian.ЙшзщЪфг.bmp" # ============== Read UTF8-encoded barcodes in various languages-encoding= # Disable encoding"{SRCDIR}PDF417.UTF8.pdf" # ============ OUPUT# Select fields in output files-fields=text,type,path,encoding # Set output files-output="{OUTDIR}utf8.xml" -output="{OUTDIR}utf8.json" -output="{OUTDIR}utf8.csv" # Set format for TEXT output-output-text="./template.txt"-output="{OUTDIR}utf8.txt"
template.txt
1234567891011121314151617181920
[onSession]{tab}SESSION: application: {app.filename}{tab} {app.version}{tab} date/time: {start.date} {start.time}[onSource]{tab|#x2}SOURCE: type: {type} path: {path}{tab|#x2} files: {files} bc.count: {bc.count}[onFile]{tab|#x3}FILE path: {path}{tab|#x3} pages: {pages} format: {format} size: {size} bc.count: {bc.count}[onPage]{tab|#x4}PAGE:path: {path} page: {page}{tab|#x4} width: {width} height: {height} bpp: {bpp} hdpi: {hdpi} vdpi: {vdpi}{tab|#x4} compr: {compr} bc.count: {bc.count}[onBarcode]{tab|#x5}BARCODE: type: {type} length: {length} {tab|#x5} rectangle: {rectangle.left}:{rectangle.top}-{rectangle.right}:{rectangle.bottom}{tab|#x5} rotation: {rotation} path: {path} page: {page}{tab|#x5} skew: {skew} mode: {mod} charset: {charset}{tab|#x5} text: {text}{tab|#x5} data: {data}[onDrvLic]{tab|#x6} DRIVER LICENSE:{tab|#x6} NAME: {last} {middle} {first}{tab|#x6} DATA: {dob} EYES: {eyes} HAIR: {hair} SEX: {sex} HEIGHT: {height} WEIGHT: {weight} {tab|#x6} ADDRESS: {street} {city} {state} {postal}{tab|#x6} LICENSE: {id} ISSUED: {issued} EXPIRES: {expires}
Read barcodes using Targeted Barcode Reader (TBR)
Windows
12345678910
@setlocal enableextensions@cd /d "%~dp0"@echo off set EXE=..\bin\BarcodeReaderCLIset OUTDIR=%TEMP%\brcliset INPDIR=.\images REM ===== Read barcode with TBR%EXE% %OPT% %AUTH% -type=datamatrix -tbr=120 -fields=+tbr "%INPDIR%\dm.tbr.bmp"
Linux
1234567891011
#!/bin/bash HERE="$(dirname "$(readlink -f "${0}")")"cd $HERE EXE=../bin/BarcodeReaderCLIOUTDIR=/tmp/brcliINPDIR=./images # ===== Read barcode with TBR$EXE $OPT $AUTH -type=datamatrix -tbr=120 -fields=+tbr "$INPDIR/dm.tbr.bmp"
Use TBR-Wizard to find the best TBR
Windows
12345678910
@setlocal enableextensions@cd /d "%~dp0"@echo off set EXE=..\bin\BarcodeReaderCLIset OUTDIR=%TEMP%\brcliset INPDIR=.\images REM ===== Find the best TBR codes for an image%EXE% tbr-wizard %OPT% %AUTH% -type=datamatrix "%INPDIR%\dm.tbr.bmp"
Linux
1234567891011
#!/bin/bash HERE="$(dirname "$(readlink -f "${0}")")"cd $HERE EXE=../bin/BarcodeReaderCLIOUTDIR=/tmp/brcliINPDIR=./images # ===== Find the best TBR codes for an image$EXE tbr-wizard $OPT $AUTH -type=datamatrix "$INPDIR/dm.tbr.bmp"