f1b30fadd30d219c03818cbff868de432d9fad45
[zxing.git] / javase / src / com / google / zxing / client / j2se / CommandLineRunner.java
1 /*
2  * Copyright 2007 ZXing authors
3  *
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
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 package com.google.zxing.client.j2se;
18
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;
31
32 import java.awt.image.BufferedImage;
33 import java.io.File;
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;
40 import java.net.URI;
41 import java.net.URISyntaxException;
42 import java.nio.charset.Charset;
43 import java.util.Hashtable;
44 import java.util.Vector;
45
46 import javax.imageio.ImageIO;
47
48 /**
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>
53  *
54  * @author Sean Owen
55  * @author dswitkin@google.com (Daniel Switkin)
56  */
57 public final class CommandLineRunner {
58
59   private CommandLineRunner() {
60   }
61
62   public static void main(String[] args) throws Exception {
63     if (args == null || args.length == 0) {
64       printUsage();
65       return;
66     }
67
68     boolean tryHarder = false;
69     boolean pureBarcode = false;
70     boolean productsOnly = false;
71     boolean dumpResults = false;
72     boolean dumpBlackPoint = false;
73     int[] crop = null;
74     for (String arg : args) {
75       if ("--try_harder".equals(arg)) {
76         tryHarder = true;
77       } else if ("--pure_barcode".equals(arg)) {
78         pureBarcode = true;
79       } else if ("--products_only".equals(arg)) {
80         productsOnly = true;
81       } else if ("--dump_results".equals(arg)) {
82         dumpResults = true;
83       } else if ("--dump_black_point".equals(arg)) {
84         dumpBlackPoint = true;
85       } else if (arg.startsWith("--crop")) {
86         crop = new int[4];
87         String[] tokens = arg.substring(7).split(",");
88         for (int i = 0; i < crop.length; i++) {
89           crop[i] = Integer.parseInt(tokens[i]);
90         }
91       } else if (arg.startsWith("-")) {
92         System.err.println("Unknown command line option " + arg);
93         printUsage();
94         return;
95       }
96     }
97
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);
102       }
103     }
104   }
105
106   // Manually turn on all formats, even those not yet considered production quality.
107   private static Hashtable<DecodeHintType, Object> buildHints(boolean tryHarder,
108                                                               boolean pureBarcode,
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);
116     if (!productsOnly) {
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);
123     }
124     hints.put(DecodeHintType.POSSIBLE_FORMATS, vector);
125     if (tryHarder) {
126       hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
127     }
128     if (pureBarcode) {
129       hints.put(DecodeHintType.PURE_BARCODE, Boolean.TRUE);
130     }
131     return hints;
132   }
133
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)");
143   }
144
145   private static void decodeOneArgument(String argument,
146                                         Hashtable<DecodeHintType, Object> hints,
147                                         boolean dumpResults,
148                                         boolean dumpBlackPoint,
149                                         int[] crop) throws IOException,
150       URISyntaxException {
151
152     File inputFile = new File(argument);
153     if (inputFile.exists()) {
154       if (inputFile.isDirectory()) {
155         int successful = 0;
156         int total = 0;
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")) {
161             continue;
162           }
163           // Skip the results of dumping the black point.
164           if (filename.contains(".mono.png")) {
165             continue;
166           }
167           Result result = decode(input.toURI(), hints, dumpBlackPoint, crop);
168           if (result != null) {
169             successful++;
170             if (dumpResults) {
171               dumpResult(input, result);
172             }
173           }
174           total++;
175         }
176         System.out.println("\nDecoded " + successful + " files out of " + total +
177             " successfully (" + (successful * 100 / total) + "%)\n");
178       } else {
179         Result result = decode(inputFile.toURI(), hints, dumpBlackPoint, crop);
180         if (dumpResults) {
181           dumpResult(inputFile, result);
182         }
183       }
184     } else {
185       decode(new URI(argument), hints, dumpBlackPoint, crop);
186     }
187   }
188
189   private static void dumpResult(File input, Result result) throws IOException {
190     String name = input.getAbsolutePath();
191     int pos = name.lastIndexOf('.');
192     if (pos > 0) {
193       name = name.substring(0, pos);
194     }
195     File dump = new File(name + ".txt");
196     writeStringToFile(result.getText(), dump);
197   }
198
199   private static void writeStringToFile(String value, File file) throws IOException {
200     Writer out = new OutputStreamWriter(new FileOutputStream(file), Charset.forName("UTF8"));
201     try {
202       out.write(value);
203     } finally {
204       out.close();
205     }
206   }
207
208   private static Result decode(URI uri,
209                                Hashtable<DecodeHintType, Object> hints,
210                                boolean dumpBlackPoint,
211                                int[] crop) throws IOException {
212     BufferedImage image;
213     try {
214       image = ImageIO.read(uri.toURL());
215     } catch (IllegalArgumentException iae) {
216       throw new FileNotFoundException("Resource not found: " + uri);
217     }
218     if (image == null) {
219       System.err.println(uri.toString() + ": Could not load image");
220       return null;
221     }
222     try {
223       LuminanceSource source;
224       if (crop == null) {
225         source = new BufferedImageLuminanceSource(image);
226       } else {
227         source = new BufferedImageLuminanceSource(image, crop[0], crop[1], crop[2], crop[3]);
228       }
229       BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
230       if (dumpBlackPoint) {
231         dumpBlackPoint(uri, image, bitmap);
232       }
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());
238       return result;
239     } catch (NotFoundException nfe) {
240       System.out.println(uri.toString() + ": No barcode found");
241       return null;
242     } finally {
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());
246     }
247   }
248
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")) {
256       return;
257     }
258
259     int width = bitmap.getWidth();
260     int height = bitmap.getHeight();
261     int stride = width * 3;
262     int[] pixels = new int[stride * height];
263
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);
269     }
270
271     // Row sampling
272     BitArray row = new BitArray(width);
273     for (int y = 0; y < height; y++) {
274       try {
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;
281         }
282         continue;
283       }
284
285       int offset = y * stride + width;
286       for (int x = 0; x < width; x++) {
287         if (row.get(x)) {
288           pixels[offset + x] = 0xff000000;
289         } else {
290           pixels[offset + x] = 0xffffffff;
291         }
292       }
293     }
294
295     // 2D sampling
296     try {
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;
303           } else {
304             pixels[offset + x] = 0xffffffff;
305           }
306         }
307       }
308     } catch (NotFoundException nfe) {
309     }
310
311     // Write the result
312     BufferedImage result = new BufferedImage(stride, height, BufferedImage.TYPE_INT_ARGB);
313     result.setRGB(0, 0, stride, height, pixels, 0, stride);
314
315     // Use the current working directory for URLs
316     String resultName = inputName;
317     if ("http".equals(uri.getScheme())) {
318       int pos = resultName.lastIndexOf('/');
319       if (pos > 0) {
320         resultName = '.' + resultName.substring(pos);
321       }
322     }
323     int pos = resultName.lastIndexOf('.');
324     if (pos > 0) {
325       resultName = resultName.substring(0, pos);
326     }
327     resultName += ".mono.png";
328     OutputStream outStream = null;
329     try {
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);
336     } finally {
337       try {
338         if (outStream != null) {
339           outStream.close();
340         }
341       } catch (IOException ioe) {
342         // continue
343       }
344     }
345   }
346
347 }