877733729dc8ce73a3e879e34e20cdf05038176e
[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     vector.addElement(BarcodeFormat.RSS14);    
117     if (!productsOnly) {
118       vector.addElement(BarcodeFormat.CODE_39);
119       vector.addElement(BarcodeFormat.CODE_93);      
120       vector.addElement(BarcodeFormat.CODE_128);
121       vector.addElement(BarcodeFormat.ITF);
122       vector.addElement(BarcodeFormat.QR_CODE);
123       vector.addElement(BarcodeFormat.DATAMATRIX);
124       vector.addElement(BarcodeFormat.PDF417);
125     }
126     hints.put(DecodeHintType.POSSIBLE_FORMATS, vector);
127     if (tryHarder) {
128       hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
129     }
130     if (pureBarcode) {
131       hints.put(DecodeHintType.PURE_BARCODE, Boolean.TRUE);
132     }
133     return hints;
134   }
135
136   private static void printUsage() {
137     System.err.println("Decode barcode images using the ZXing library\n");
138     System.err.println("usage: CommandLineRunner { file | dir | url } [ options ]");
139     System.err.println("  --try_harder: Use the TRY_HARDER hint, default is normal (mobile) mode");
140     System.err.println("  --pure_barcode: Input image is a pure monochrome barcode image, not a photo");
141     System.err.println("  --products_only: Only decode the UPC and EAN families of barcodes");
142     System.err.println("  --dump_results: Write the decoded contents to input.txt");
143     System.err.println("  --dump_black_point: Compare black point algorithms as input.mono.png");
144     System.err.println("  --crop=left,top,width,height: Only examine cropped region of input image(s)");
145   }
146
147   private static void decodeOneArgument(String argument,
148                                         Hashtable<DecodeHintType, Object> hints,
149                                         boolean dumpResults,
150                                         boolean dumpBlackPoint,
151                                         int[] crop) throws IOException,
152       URISyntaxException {
153
154     File inputFile = new File(argument);
155     if (inputFile.exists()) {
156       if (inputFile.isDirectory()) {
157         int successful = 0;
158         int total = 0;
159         for (File input : inputFile.listFiles()) {
160           String filename = input.getName().toLowerCase();
161           // Skip hidden files and text files (the latter is found in the blackbox tests).
162           if (filename.startsWith(".") || filename.endsWith(".txt")) {
163             continue;
164           }
165           // Skip the results of dumping the black point.
166           if (filename.contains(".mono.png")) {
167             continue;
168           }
169           Result result = decode(input.toURI(), hints, dumpBlackPoint, crop);
170           if (result != null) {
171             successful++;
172             if (dumpResults) {
173               dumpResult(input, result);
174             }
175           }
176           total++;
177         }
178         System.out.println("\nDecoded " + successful + " files out of " + total +
179             " successfully (" + (successful * 100 / total) + "%)\n");
180       } else {
181         Result result = decode(inputFile.toURI(), hints, dumpBlackPoint, crop);
182         if (dumpResults) {
183           dumpResult(inputFile, result);
184         }
185       }
186     } else {
187       decode(new URI(argument), hints, dumpBlackPoint, crop);
188     }
189   }
190
191   private static void dumpResult(File input, Result result) throws IOException {
192     String name = input.getAbsolutePath();
193     int pos = name.lastIndexOf('.');
194     if (pos > 0) {
195       name = name.substring(0, pos);
196     }
197     File dump = new File(name + ".txt");
198     writeStringToFile(result.getText(), dump);
199   }
200
201   private static void writeStringToFile(String value, File file) throws IOException {
202     Writer out = new OutputStreamWriter(new FileOutputStream(file), Charset.forName("UTF8"));
203     try {
204       out.write(value);
205     } finally {
206       out.close();
207     }
208   }
209
210   private static Result decode(URI uri,
211                                Hashtable<DecodeHintType, Object> hints,
212                                boolean dumpBlackPoint,
213                                int[] crop) throws IOException {
214     BufferedImage image;
215     try {
216       image = ImageIO.read(uri.toURL());
217     } catch (IllegalArgumentException iae) {
218       throw new FileNotFoundException("Resource not found: " + uri);
219     }
220     if (image == null) {
221       System.err.println(uri.toString() + ": Could not load image");
222       return null;
223     }
224     try {
225       LuminanceSource source;
226       if (crop == null) {
227         source = new BufferedImageLuminanceSource(image);
228       } else {
229         source = new BufferedImageLuminanceSource(image, crop[0], crop[1], crop[2], crop[3]);
230       }
231       BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
232       if (dumpBlackPoint) {
233         dumpBlackPoint(uri, image, bitmap);
234       }
235       Result result = new MultiFormatReader().decode(bitmap, hints);
236       ParsedResult parsedResult = ResultParser.parseResult(result);
237       System.out.println(uri.toString() + " (format: " + result.getBarcodeFormat() +
238           ", type: " + parsedResult.getType() + "):\nRaw result:\n" + result.getText() +
239           "\nParsed result:\n" + parsedResult.getDisplayResult());
240       return result;
241     } catch (NotFoundException nfe) {
242       System.out.println(uri.toString() + ": No barcode found");
243       return null;
244     } finally {
245       // Uncomment these lines when turning on exception tracking in ReaderException.
246       //System.out.println("Threw " + ReaderException.getExceptionCountAndReset() + " exceptions");
247       //System.out.println("Throwers:\n" + ReaderException.getThrowersAndReset());
248     }
249   }
250
251   // Writes out a single PNG which is three times the width of the input image, containing from left
252   // to right: the original image, the row sampling monochrome version, and the 2D sampling
253   // monochrome version.
254   // TODO: Update to compare different Binarizer implementations.
255   private static void dumpBlackPoint(URI uri, BufferedImage image, BinaryBitmap bitmap) {
256     String inputName = uri.getPath();
257     if (inputName.contains(".mono.png")) {
258       return;
259     }
260
261     int width = bitmap.getWidth();
262     int height = bitmap.getHeight();
263     int stride = width * 3;
264     int[] pixels = new int[stride * height];
265
266     // The original image
267     int[] argb = new int[width];
268     for (int y = 0; y < height; y++) {
269       image.getRGB(0, y, width, 1, argb, 0, width);
270       System.arraycopy(argb, 0, pixels, y * stride, width);
271     }
272
273     // Row sampling
274     BitArray row = new BitArray(width);
275     for (int y = 0; y < height; y++) {
276       try {
277         row = bitmap.getBlackRow(y, row);
278       } catch (NotFoundException nfe) {
279         // If fetching the row failed, draw a red line and keep going.
280         int offset = y * stride + width;
281         for (int x = 0; x < width; x++) {
282           pixels[offset + x] = 0xffff0000;
283         }
284         continue;
285       }
286
287       int offset = y * stride + width;
288       for (int x = 0; x < width; x++) {
289         if (row.get(x)) {
290           pixels[offset + x] = 0xff000000;
291         } else {
292           pixels[offset + x] = 0xffffffff;
293         }
294       }
295     }
296
297     // 2D sampling
298     try {
299       for (int y = 0; y < height; y++) {
300         BitMatrix matrix = bitmap.getBlackMatrix();
301         int offset = y * stride + width * 2;
302         for (int x = 0; x < width; x++) {
303           if (matrix.get(x, y)) {
304             pixels[offset + x] = 0xff000000;
305           } else {
306             pixels[offset + x] = 0xffffffff;
307           }
308         }
309       }
310     } catch (NotFoundException nfe) {
311     }
312
313     // Write the result
314     BufferedImage result = new BufferedImage(stride, height, BufferedImage.TYPE_INT_ARGB);
315     result.setRGB(0, 0, stride, height, pixels, 0, stride);
316
317     // Use the current working directory for URLs
318     String resultName = inputName;
319     if ("http".equals(uri.getScheme())) {
320       int pos = resultName.lastIndexOf('/');
321       if (pos > 0) {
322         resultName = '.' + resultName.substring(pos);
323       }
324     }
325     int pos = resultName.lastIndexOf('.');
326     if (pos > 0) {
327       resultName = resultName.substring(0, pos);
328     }
329     resultName += ".mono.png";
330     OutputStream outStream = null;
331     try {
332       outStream = new FileOutputStream(resultName);
333       ImageIO.write(result, "png", outStream);
334     } catch (FileNotFoundException e) {
335       System.err.println("Could not create " + resultName);
336     } catch (IOException e) {
337       System.err.println("Could not write to " + resultName);
338     } finally {
339       try {
340         if (outStream != null) {
341           outStream.close();
342         }
343       } catch (IOException ioe) {
344         // continue
345       }
346     }
347   }
348
349 }