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