2 * Copyright 2007 ZXing authors
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 package com.google.zxing.client.j2se;
19 import com.google.zxing.BarcodeFormat;
20 import com.google.zxing.BinaryBitmap;
21 import com.google.zxing.DecodeHintType;
22 import com.google.zxing.LuminanceSource;
23 import com.google.zxing.MultiFormatReader;
24 import com.google.zxing.NotFoundException;
25 import com.google.zxing.Result;
26 import com.google.zxing.client.result.ParsedResult;
27 import com.google.zxing.client.result.ResultParser;
28 import com.google.zxing.common.BitArray;
29 import com.google.zxing.common.BitMatrix;
30 import com.google.zxing.common.HybridBinarizer;
32 import java.awt.image.BufferedImage;
34 import java.io.FileNotFoundException;
35 import java.io.FileOutputStream;
36 import java.io.IOException;
37 import java.io.OutputStream;
38 import java.io.OutputStreamWriter;
39 import java.io.Writer;
41 import java.net.URISyntaxException;
42 import java.nio.charset.Charset;
43 import java.util.Hashtable;
44 import java.util.Vector;
46 import javax.imageio.ImageIO;
49 * <p>This simple command line utility decodes files, directories of files, or URIs which are passed
50 * as arguments. By default it uses the normal decoding algorithms, but you can pass --try_harder to
51 * request that hint. The raw text of each barcode is printed, and when running against directories,
52 * summary statistics are also displayed.</p>
55 * @author dswitkin@google.com (Daniel Switkin)
57 public final class CommandLineRunner {
59 private CommandLineRunner() {
62 public static void main(String[] args) throws Exception {
63 if (args == null || args.length == 0) {
68 boolean tryHarder = false;
69 boolean pureBarcode = false;
70 boolean productsOnly = false;
71 boolean dumpResults = false;
72 boolean dumpBlackPoint = false;
73 for (String arg : args) {
74 if ("--try_harder".equals(arg)) {
76 } else if ("--pure_barcode".equals(arg)) {
78 } else if ("--products_only".equals(arg)) {
80 } else if ("--dump_results".equals(arg)) {
82 } else if ("--dump_black_point".equals(arg)) {
83 dumpBlackPoint = true;
84 } else if (arg.startsWith("-")) {
85 System.err.println("Unknown command line option " + arg);
91 Hashtable<DecodeHintType, Object> hints = buildHints(tryHarder, pureBarcode, productsOnly);
92 for (String arg : args) {
93 if (!arg.startsWith("--")) {
94 decodeOneArgument(arg, hints, dumpResults, dumpBlackPoint);
99 // Manually turn on all formats, even those not yet considered production quality.
100 private static Hashtable<DecodeHintType, Object> buildHints(boolean tryHarder,
102 boolean productsOnly) {
103 Hashtable<DecodeHintType, Object> hints = new Hashtable<DecodeHintType, Object>(3);
104 Vector<BarcodeFormat> vector = new Vector<BarcodeFormat>(8);
105 vector.addElement(BarcodeFormat.UPC_A);
106 vector.addElement(BarcodeFormat.UPC_E);
107 vector.addElement(BarcodeFormat.EAN_13);
108 vector.addElement(BarcodeFormat.EAN_8);
110 vector.addElement(BarcodeFormat.CODE_39);
111 vector.addElement(BarcodeFormat.CODE_128);
112 vector.addElement(BarcodeFormat.ITF);
113 vector.addElement(BarcodeFormat.QR_CODE);
114 vector.addElement(BarcodeFormat.DATAMATRIX);
115 vector.addElement(BarcodeFormat.PDF417);
117 hints.put(DecodeHintType.POSSIBLE_FORMATS, vector);
119 hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
122 hints.put(DecodeHintType.PURE_BARCODE, Boolean.TRUE);
127 private static void printUsage() {
128 System.err.println("Decode barcode images using the ZXing library\n");
129 System.err.println("usage: CommandLineRunner { file | dir | url } [ options ]");
130 System.err.println(" --try_harder: Use the TRY_HARDER hint, default is normal (mobile) mode");
131 System.err.println(" --products_only: Only decode the UPC and EAN families of barcodes");
132 System.err.println(" --dump_results: Write the decoded contents to input.txt");
133 System.err.println(" --dump_black_point: Compare black point algorithms as input.mono.png");
136 private static void decodeOneArgument(String argument, Hashtable<DecodeHintType, Object> hints,
137 boolean dumpResults, boolean dumpBlackPoint) throws IOException,
140 File inputFile = new File(argument);
141 if (inputFile.exists()) {
142 if (inputFile.isDirectory()) {
145 for (File input : inputFile.listFiles()) {
146 String filename = input.getName().toLowerCase();
147 // Skip hidden files and text files (the latter is found in the blackbox tests).
148 if (filename.startsWith(".") || filename.endsWith(".txt")) {
151 // Skip the results of dumping the black point.
152 if (filename.contains(".mono.png")) {
155 Result result = decode(input.toURI(), hints, dumpBlackPoint);
156 if (result != null) {
159 dumpResult(input, result);
164 System.out.println("\nDecoded " + successful + " files out of " + total +
165 " successfully (" + (successful * 100 / total) + "%)\n");
167 Result result = decode(inputFile.toURI(), hints, dumpBlackPoint);
169 dumpResult(inputFile, result);
173 decode(new URI(argument), hints, dumpBlackPoint);
177 private static void dumpResult(File input, Result result) throws IOException {
178 String name = input.getAbsolutePath();
179 int pos = name.lastIndexOf('.');
181 name = name.substring(0, pos);
183 File dump = new File(name + ".txt");
184 writeStringToFile(result.getText(), dump);
187 private static void writeStringToFile(String value, File file) throws IOException {
188 Writer out = new OutputStreamWriter(new FileOutputStream(file), Charset.forName("UTF8"));
196 private static Result decode(URI uri, Hashtable<DecodeHintType, Object> hints,
197 boolean dumpBlackPoint) throws IOException {
200 image = ImageIO.read(uri.toURL());
201 } catch (IllegalArgumentException iae) {
202 throw new FileNotFoundException("Resource not found: " + uri);
205 System.err.println(uri.toString() + ": Could not load image");
209 LuminanceSource source = new BufferedImageLuminanceSource(image);
210 BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
211 if (dumpBlackPoint) {
212 dumpBlackPoint(uri, image, bitmap);
214 Result result = new MultiFormatReader().decode(bitmap, hints);
215 ParsedResult parsedResult = ResultParser.parseResult(result);
216 System.out.println(uri.toString() + " (format: " + result.getBarcodeFormat() +
217 ", type: " + parsedResult.getType() + "):\nRaw result:\n" + result.getText() +
218 "\nParsed result:\n" + parsedResult.getDisplayResult());
220 } catch (NotFoundException nfe) {
221 System.out.println(uri.toString() + ": No barcode found");
224 // Uncomment these lines when turning on exception tracking in ReaderException.
225 //System.out.println("Threw " + ReaderException.getExceptionCountAndReset() + " exceptions");
226 //System.out.println("Throwers:\n" + ReaderException.getThrowersAndReset());
230 // Writes out a single PNG which is three times the width of the input image, containing from left
231 // to right: the original image, the row sampling monochrome version, and the 2D sampling
232 // monochrome version.
233 // TODO: Update to compare different Binarizer implementations.
234 private static void dumpBlackPoint(URI uri, BufferedImage image, BinaryBitmap bitmap) {
235 String inputName = uri.getPath();
236 if (inputName.contains(".mono.png")) {
240 int width = bitmap.getWidth();
241 int height = bitmap.getHeight();
242 int stride = width * 3;
243 int[] pixels = new int[stride * height];
245 // The original image
246 int[] argb = new int[width];
247 for (int y = 0; y < height; y++) {
248 image.getRGB(0, y, width, 1, argb, 0, width);
249 System.arraycopy(argb, 0, pixels, y * stride, width);
253 BitArray row = new BitArray(width);
254 for (int y = 0; y < height; y++) {
256 row = bitmap.getBlackRow(y, row);
257 } catch (NotFoundException nfe) {
258 // If fetching the row failed, draw a red line and keep going.
259 int offset = y * stride + width;
260 for (int x = 0; x < width; x++) {
261 pixels[offset + x] = 0xffff0000;
266 int offset = y * stride + width;
267 for (int x = 0; x < width; x++) {
269 pixels[offset + x] = 0xff000000;
271 pixels[offset + x] = 0xffffffff;
278 for (int y = 0; y < height; y++) {
279 BitMatrix matrix = bitmap.getBlackMatrix();
280 int offset = y * stride + width * 2;
281 for (int x = 0; x < width; x++) {
282 if (matrix.get(x, y)) {
283 pixels[offset + x] = 0xff000000;
285 pixels[offset + x] = 0xffffffff;
289 } catch (NotFoundException nfe) {
293 BufferedImage result = new BufferedImage(stride, height, BufferedImage.TYPE_INT_ARGB);
294 result.setRGB(0, 0, stride, height, pixels, 0, stride);
296 // Use the current working directory for URLs
297 String resultName = inputName;
298 if ("http".equals(uri.getScheme())) {
299 int pos = resultName.lastIndexOf('/');
301 resultName = '.' + resultName.substring(pos);
304 int pos = resultName.lastIndexOf('.');
306 resultName = resultName.substring(0, pos);
308 resultName += ".mono.png";
309 OutputStream outStream = null;
311 outStream = new FileOutputStream(resultName);
312 ImageIO.write(result, "png", outStream);
313 } catch (FileNotFoundException e) {
314 System.err.println("Could not create " + resultName);
315 } catch (IOException e) {
316 System.err.println("Could not write to " + resultName);
319 if (outStream != null) {
322 } catch (IOException ioe) {