Wrote a usage message for the CommandLineRunner.
[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.BlackPointEstimationMethod;
20 import com.google.zxing.DecodeHintType;
21 import com.google.zxing.MonochromeBitmapSource;
22 import com.google.zxing.MultiFormatReader;
23 import com.google.zxing.ReaderException;
24 import com.google.zxing.Result;
25 import com.google.zxing.client.result.ParsedResult;
26 import com.google.zxing.client.result.ResultParser;
27 import com.google.zxing.common.BitArray;
28
29 import javax.imageio.ImageIO;
30 import java.awt.image.BufferedImage;
31 import java.io.File;
32 import java.io.FileNotFoundException;
33 import java.io.FileOutputStream;
34 import java.io.IOException;
35 import java.io.OutputStream;
36 import java.io.OutputStreamWriter;
37 import java.io.Writer;
38 import java.net.URI;
39 import java.net.URISyntaxException;
40 import java.nio.charset.Charset;
41 import java.util.Hashtable;
42
43 /**
44  * <p>This simple command line utility decodes files, directories of files, or URIs which are passed
45  * as arguments. By default it uses the normal decoding algorithms, but you can pass --try_harder to
46  * request that hint. The raw text of each barcode is printed, and when running against directories,
47  * summary statistics are also displayed.</p>
48  *
49  * @author Sean Owen
50  * @author dswitkin@google.com (Daniel Switkin)
51  */
52 public final class CommandLineRunner {
53
54   private CommandLineRunner() {
55   }
56
57   public static void main(String[] args) throws Exception {
58     if (args == null || args.length == 0) {
59       printUsage();
60       return;
61     }
62     Hashtable<DecodeHintType, Object> hints = null;
63     boolean dumpResults = false;
64     boolean dumpBlackPoint = false;
65     for (String arg : args) {
66       if ("--try_harder".equals(arg)) {
67         hints = new Hashtable<DecodeHintType, Object>(3);
68         hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
69       } else if ("--dump_results".equals(arg)) {
70         dumpResults = true;
71       } else if ("--dump_black_point".equals(arg)) {
72         dumpBlackPoint = true;
73       } else if (arg.startsWith("-")) {
74         System.out.println("Unknown command line option " + arg);
75         printUsage();
76         return;
77       }
78     }
79     for (String arg : args) {
80       if (!arg.startsWith("--")) {
81         decodeOneArgument(arg, hints, dumpResults, dumpBlackPoint);
82       }
83     }
84   }
85
86   private static void printUsage() {
87     System.out.println("Decode barcode images using the ZXing library\n");
88     System.out.println("usage: CommandLineRunner { file | dir | url } [ options ]");
89     System.out.println("  --try_harder: Use the TRY_HARDER hint, default is normal (mobile) mode");
90     System.out.println("  --dump_results: Write the decoded contents to input.txt");
91     System.out.println("  --dump_black_point: Compare black point algorithms as input.mono.png");
92   }
93
94   private static void decodeOneArgument(String argument, Hashtable<DecodeHintType, Object> hints,
95       boolean dumpResults, boolean dumpBlackPoint) throws IOException,
96       URISyntaxException {
97
98     File inputFile = new File(argument);
99     if (inputFile.exists()) {
100       if (inputFile.isDirectory()) {
101         int successful = 0;
102         int total = 0;
103         for (File input : inputFile.listFiles()) {
104           String filename = input.getName().toLowerCase();
105           // Skip hidden files and text files (the latter is found in the blackbox tests).
106           if (filename.startsWith(".") || filename.endsWith(".txt")) {
107             continue;
108           }
109           // Skip the results of dumping the black point.
110           if (filename.contains(".mono.png")) {
111             continue;
112           }
113           Result result = decode(input.toURI(), hints, dumpBlackPoint);
114           if (result != null) {
115             successful++;
116             if (dumpResults) {
117               dumpResult(input, result);
118             }
119           }
120           total++;
121         }
122         System.out.println("\nDecoded " + successful + " files out of " + total +
123             " successfully (" + (successful * 100 / total) + "%)\n");
124       } else {
125         Result result = decode(inputFile.toURI(), hints, dumpBlackPoint);
126         if (dumpResults) {
127           dumpResult(inputFile, result);
128         }
129       }
130     } else {
131       decode(new URI(argument), hints, dumpBlackPoint);
132     }
133   }
134
135   private static void dumpResult(File input, Result result) throws IOException {
136     String name = input.getAbsolutePath();
137     int pos = name.lastIndexOf('.');
138     if (pos > 0) {
139       name = name.substring(0, pos);
140     }
141     File dump = new File(name + ".txt");
142     writeStringToFile(result.getText(), dump);
143   }
144
145   private static void writeStringToFile(String value, File file) throws IOException {
146     Writer out = new OutputStreamWriter(new FileOutputStream(file), Charset.forName("UTF8"));
147     try {
148       out.write(value);
149     } finally {
150       out.close();
151     }
152   }
153
154   private static Result decode(URI uri, Hashtable<DecodeHintType, Object> hints,
155       boolean dumpBlackPoint) throws IOException {
156     BufferedImage image;
157     try {
158       image = ImageIO.read(uri.toURL());
159     } catch (IllegalArgumentException iae) {
160       throw new FileNotFoundException("Resource not found: " + uri);
161     }
162     if (image == null) {
163       System.err.println(uri.toString() + ": Could not load image");
164       return null;
165     }
166     try {
167       MonochromeBitmapSource source = new BufferedImageMonochromeBitmapSource(image);
168       if (dumpBlackPoint) {
169         dumpBlackPoint(uri, image, source);
170       }
171       Result result = new MultiFormatReader().decode(source, hints);
172       ParsedResult parsedResult = ResultParser.parseResult(result);
173       System.out.println(uri.toString() + " (format: " + result.getBarcodeFormat() +
174           ", type: " + parsedResult.getType() + "):\nRaw result:\n" + result.getText() +
175           "\nParsed result:\n" + parsedResult.getDisplayResult());
176       return result;
177     } catch (ReaderException e) {
178       System.out.println(uri.toString() + ": No barcode found");
179       return null;
180     }
181   }
182
183   // Writes out a single PNG which is three times the width of the input image, containing from left
184   // to right: the original image, the row sampling monochrome version, and the 2D sampling
185   // monochrome version.
186   private static void dumpBlackPoint(URI uri, BufferedImage image, MonochromeBitmapSource source) {
187     String inputName = uri.getPath();
188     if (inputName.contains(".mono.png")) {
189       return;
190     }
191
192     int width = source.getWidth();
193     int height = source.getHeight();
194     int stride = width * 3;
195     int[] pixels = new int[stride * height];
196
197     // The original image
198     int[] argb = new int[width];
199     for (int y = 0; y < height; y++) {
200       image.getRGB(0, y, width, 1, argb, 0, width);
201       System.arraycopy(argb, 0, pixels, y * stride, width);
202     }
203     argb = null;
204
205     // Row sampling
206     BitArray row = new BitArray(width);
207     for (int y = 0; y < height; y++) {
208       try {
209         source.estimateBlackPoint(BlackPointEstimationMethod.ROW_SAMPLING, y);
210       } catch (ReaderException e) {
211         // If the row histogram failed, draw a red line and keep going
212         int offset = y * stride + width;
213         for (int x = 0; x < width; x++) {
214           pixels[offset + x] = 0xffff0000;
215         }
216         continue;
217       }
218       source.getBlackRow(y, row, 0, width);
219       int offset = y * stride + width;
220       for (int x = 0; x < width; x++) {
221         if (row.get(x)) {
222           pixels[offset + x] = 0xff000000;
223         } else {
224           pixels[offset + x] = 0xffffffff;
225         }
226       }
227     }
228
229     // 2D sampling
230     try {
231       source.estimateBlackPoint(BlackPointEstimationMethod.TWO_D_SAMPLING, 0);
232       for (int y = 0; y < height; y++) {
233         source.getBlackRow(y, row, 0, width);
234         int offset = y * stride + width * 2;
235         for (int x = 0; x < width; x++) {
236           if (row.get(x)) {
237             pixels[offset + x] = 0xff000000;
238           } else {
239             pixels[offset + x] = 0xffffffff;
240           }
241         }
242       }
243     } catch (ReaderException e) {
244     }
245
246     // Write the result
247     BufferedImage result = new BufferedImage(stride, height, BufferedImage.TYPE_INT_ARGB);
248     result.setRGB(0, 0, stride, height, pixels, 0, stride);
249
250     // Use the current working directory for URLs
251     String resultName = inputName;
252     if (uri.getScheme().equals("http")) {
253       int pos = resultName.lastIndexOf('/');
254       if (pos > 0) {
255         resultName = "." + resultName.substring(pos);
256       }
257     }
258     int pos = resultName.lastIndexOf('.');
259     if (pos > 0) {
260       resultName = resultName.substring(0, pos);
261     }
262     resultName += ".mono.png";
263     try {
264       OutputStream outStream = new FileOutputStream(resultName);
265       ImageIO.write(result, "png", outStream);
266     } catch (FileNotFoundException e) {
267       System.out.println("Could not create " + resultName);
268     } catch (IOException e) {
269       System.out.println("Could not write to " + resultName);
270     }
271   }
272
273 }