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;
74 for (String arg : args) {
75 if ("--try_harder".equals(arg)) {
77 } else if ("--pure_barcode".equals(arg)) {
79 } else if ("--products_only".equals(arg)) {
81 } else if ("--dump_results".equals(arg)) {
83 } else if ("--dump_black_point".equals(arg)) {
84 dumpBlackPoint = true;
85 } else if (arg.startsWith("--crop")) {
87 String[] tokens = arg.substring(7).split(",");
88 for (int i = 0; i < crop.length; i++) {
89 crop[i] = Integer.parseInt(tokens[i]);
91 } else if (arg.startsWith("-")) {
92 System.err.println("Unknown command line option " + arg);
98 Hashtable<DecodeHintType, Object> hints = buildHints(tryHarder, pureBarcode, productsOnly);
99 for (String arg : args) {
100 if (!arg.startsWith("--")) {
101 decodeOneArgument(arg, hints, dumpResults, dumpBlackPoint, crop);
106 // Manually turn on all formats, even those not yet considered production quality.
107 private static Hashtable<DecodeHintType, Object> buildHints(boolean tryHarder,
109 boolean productsOnly) {
110 Hashtable<DecodeHintType, Object> hints = new Hashtable<DecodeHintType, Object>(3);
111 Vector<BarcodeFormat> vector = new Vector<BarcodeFormat>(8);
112 vector.addElement(BarcodeFormat.UPC_A);
113 vector.addElement(BarcodeFormat.UPC_E);
114 vector.addElement(BarcodeFormat.EAN_13);
115 vector.addElement(BarcodeFormat.EAN_8);
117 vector.addElement(BarcodeFormat.CODE_39);
118 vector.addElement(BarcodeFormat.CODE_128);
119 vector.addElement(BarcodeFormat.ITF);
120 vector.addElement(BarcodeFormat.QR_CODE);
121 vector.addElement(BarcodeFormat.DATAMATRIX);
122 vector.addElement(BarcodeFormat.PDF417);
124 hints.put(DecodeHintType.POSSIBLE_FORMATS, vector);
126 hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
129 hints.put(DecodeHintType.PURE_BARCODE, Boolean.TRUE);
134 private static void printUsage() {
135 System.err.println("Decode barcode images using the ZXing library\n");
136 System.err.println("usage: CommandLineRunner { file | dir | url } [ options ]");
137 System.err.println(" --try_harder: Use the TRY_HARDER hint, default is normal (mobile) mode");
138 System.err.println(" --pure_barcode: Input image is a pure monochrome barcode image, not a photo");
139 System.err.println(" --products_only: Only decode the UPC and EAN families of barcodes");
140 System.err.println(" --dump_results: Write the decoded contents to input.txt");
141 System.err.println(" --dump_black_point: Compare black point algorithms as input.mono.png");
142 System.err.println(" --crop=left,top,width,height: Only examine cropped region of input image(s)");
145 private static void decodeOneArgument(String argument,
146 Hashtable<DecodeHintType, Object> hints,
148 boolean dumpBlackPoint,
149 int[] crop) throws IOException,
152 File inputFile = new File(argument);
153 if (inputFile.exists()) {
154 if (inputFile.isDirectory()) {
157 for (File input : inputFile.listFiles()) {
158 String filename = input.getName().toLowerCase();
159 // Skip hidden files and text files (the latter is found in the blackbox tests).
160 if (filename.startsWith(".") || filename.endsWith(".txt")) {
163 // Skip the results of dumping the black point.
164 if (filename.contains(".mono.png")) {
167 Result result = decode(input.toURI(), hints, dumpBlackPoint, crop);
168 if (result != null) {
171 dumpResult(input, result);
176 System.out.println("\nDecoded " + successful + " files out of " + total +
177 " successfully (" + (successful * 100 / total) + "%)\n");
179 Result result = decode(inputFile.toURI(), hints, dumpBlackPoint, crop);
181 dumpResult(inputFile, result);
185 decode(new URI(argument), hints, dumpBlackPoint, crop);
189 private static void dumpResult(File input, Result result) throws IOException {
190 String name = input.getAbsolutePath();
191 int pos = name.lastIndexOf('.');
193 name = name.substring(0, pos);
195 File dump = new File(name + ".txt");
196 writeStringToFile(result.getText(), dump);
199 private static void writeStringToFile(String value, File file) throws IOException {
200 Writer out = new OutputStreamWriter(new FileOutputStream(file), Charset.forName("UTF8"));
208 private static Result decode(URI uri,
209 Hashtable<DecodeHintType, Object> hints,
210 boolean dumpBlackPoint,
211 int[] crop) throws IOException {
214 image = ImageIO.read(uri.toURL());
215 } catch (IllegalArgumentException iae) {
216 throw new FileNotFoundException("Resource not found: " + uri);
219 System.err.println(uri.toString() + ": Could not load image");
223 LuminanceSource source;
225 source = new BufferedImageLuminanceSource(image);
227 source = new BufferedImageLuminanceSource(image, crop[0], crop[1], crop[2], crop[3]);
229 BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
230 if (dumpBlackPoint) {
231 dumpBlackPoint(uri, image, bitmap);
233 Result result = new MultiFormatReader().decode(bitmap, hints);
234 ParsedResult parsedResult = ResultParser.parseResult(result);
235 System.out.println(uri.toString() + " (format: " + result.getBarcodeFormat() +
236 ", type: " + parsedResult.getType() + "):\nRaw result:\n" + result.getText() +
237 "\nParsed result:\n" + parsedResult.getDisplayResult());
239 } catch (NotFoundException nfe) {
240 System.out.println(uri.toString() + ": No barcode found");
243 // Uncomment these lines when turning on exception tracking in ReaderException.
244 //System.out.println("Threw " + ReaderException.getExceptionCountAndReset() + " exceptions");
245 //System.out.println("Throwers:\n" + ReaderException.getThrowersAndReset());
249 // Writes out a single PNG which is three times the width of the input image, containing from left
250 // to right: the original image, the row sampling monochrome version, and the 2D sampling
251 // monochrome version.
252 // TODO: Update to compare different Binarizer implementations.
253 private static void dumpBlackPoint(URI uri, BufferedImage image, BinaryBitmap bitmap) {
254 String inputName = uri.getPath();
255 if (inputName.contains(".mono.png")) {
259 int width = bitmap.getWidth();
260 int height = bitmap.getHeight();
261 int stride = width * 3;
262 int[] pixels = new int[stride * height];
264 // The original image
265 int[] argb = new int[width];
266 for (int y = 0; y < height; y++) {
267 image.getRGB(0, y, width, 1, argb, 0, width);
268 System.arraycopy(argb, 0, pixels, y * stride, width);
272 BitArray row = new BitArray(width);
273 for (int y = 0; y < height; y++) {
275 row = bitmap.getBlackRow(y, row);
276 } catch (NotFoundException nfe) {
277 // If fetching the row failed, draw a red line and keep going.
278 int offset = y * stride + width;
279 for (int x = 0; x < width; x++) {
280 pixels[offset + x] = 0xffff0000;
285 int offset = y * stride + width;
286 for (int x = 0; x < width; x++) {
288 pixels[offset + x] = 0xff000000;
290 pixels[offset + x] = 0xffffffff;
297 for (int y = 0; y < height; y++) {
298 BitMatrix matrix = bitmap.getBlackMatrix();
299 int offset = y * stride + width * 2;
300 for (int x = 0; x < width; x++) {
301 if (matrix.get(x, y)) {
302 pixels[offset + x] = 0xff000000;
304 pixels[offset + x] = 0xffffffff;
308 } catch (NotFoundException nfe) {
312 BufferedImage result = new BufferedImage(stride, height, BufferedImage.TYPE_INT_ARGB);
313 result.setRGB(0, 0, stride, height, pixels, 0, stride);
315 // Use the current working directory for URLs
316 String resultName = inputName;
317 if ("http".equals(uri.getScheme())) {
318 int pos = resultName.lastIndexOf('/');
320 resultName = '.' + resultName.substring(pos);
323 int pos = resultName.lastIndexOf('.');
325 resultName = resultName.substring(0, pos);
327 resultName += ".mono.png";
328 OutputStream outStream = null;
330 outStream = new FileOutputStream(resultName);
331 ImageIO.write(result, "png", outStream);
332 } catch (FileNotFoundException e) {
333 System.err.println("Could not create " + resultName);
334 } catch (IOException e) {
335 System.err.println("Could not write to " + resultName);
338 if (outStream != null) {
341 } catch (IOException ioe) {