a607cd68f60b1bcff9706aad1f03b5a5a8d88285
[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.BinaryBitmap;
20 import com.google.zxing.DecodeHintType;
21 import com.google.zxing.LuminanceSource;
22 import com.google.zxing.MultiFormatReader;
23 import com.google.zxing.ReaderException;
24 import com.google.zxing.Result;
25 import com.google.zxing.BarcodeFormat;
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.GlobalHistogramBinarizer;
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     Hashtable<DecodeHintType, Object> hints = buildHints();
68     boolean dumpResults = false;
69     boolean dumpBlackPoint = false;
70     for (String arg : args) {
71       if ("--try_harder".equals(arg)) {
72         hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
73       } else if ("--dump_results".equals(arg)) {
74         dumpResults = true;
75       } else if ("--dump_black_point".equals(arg)) {
76         dumpBlackPoint = true;
77       } else if (arg.startsWith("-")) {
78         System.err.println("Unknown command line option " + arg);
79         printUsage();
80         return;
81       }
82     }
83     for (String arg : args) {
84       if (!arg.startsWith("--")) {
85         decodeOneArgument(arg, hints, dumpResults, dumpBlackPoint);
86       }
87     }
88   }
89
90   // Manually turn on all formats, even those not yet considered production quality.
91   private static Hashtable<DecodeHintType, Object> buildHints() {
92     Hashtable<DecodeHintType, Object> hints = new Hashtable<DecodeHintType, Object>(3);
93     Vector<BarcodeFormat> vector = new Vector<BarcodeFormat>(8);
94     vector.addElement(BarcodeFormat.UPC_A);
95     vector.addElement(BarcodeFormat.UPC_E);
96     vector.addElement(BarcodeFormat.EAN_13);
97     vector.addElement(BarcodeFormat.EAN_8);
98     vector.addElement(BarcodeFormat.CODE_39);
99     vector.addElement(BarcodeFormat.CODE_128);
100     vector.addElement(BarcodeFormat.ITF);
101     vector.addElement(BarcodeFormat.QR_CODE);
102     vector.addElement(BarcodeFormat.DATAMATRIX);
103     vector.addElement(BarcodeFormat.PDF417);
104     hints.put(DecodeHintType.POSSIBLE_FORMATS, vector);
105     return hints;
106   }
107
108   private static void printUsage() {
109     System.err.println("Decode barcode images using the ZXing library\n");
110     System.err.println("usage: CommandLineRunner { file | dir | url } [ options ]");
111     System.err.println("  --try_harder: Use the TRY_HARDER hint, default is normal (mobile) mode");
112     System.err.println("  --dump_results: Write the decoded contents to input.txt");
113     System.err.println("  --dump_black_point: Compare black point algorithms as input.mono.png");
114   }
115
116   private static void decodeOneArgument(String argument, Hashtable<DecodeHintType, Object> hints,
117       boolean dumpResults, boolean dumpBlackPoint) throws IOException,
118       URISyntaxException {
119
120     File inputFile = new File(argument);
121     if (inputFile.exists()) {
122       if (inputFile.isDirectory()) {
123         int successful = 0;
124         int total = 0;
125         for (File input : inputFile.listFiles()) {
126           String filename = input.getName().toLowerCase();
127           // Skip hidden files and text files (the latter is found in the blackbox tests).
128           if (filename.startsWith(".") || filename.endsWith(".txt")) {
129             continue;
130           }
131           // Skip the results of dumping the black point.
132           if (filename.contains(".mono.png")) {
133             continue;
134           }
135           Result result = decode(input.toURI(), hints, dumpBlackPoint);
136           if (result != null) {
137             successful++;
138             if (dumpResults) {
139               dumpResult(input, result);
140             }
141           }
142           total++;
143         }
144         System.out.println("\nDecoded " + successful + " files out of " + total +
145             " successfully (" + (successful * 100 / total) + "%)\n");
146       } else {
147         Result result = decode(inputFile.toURI(), hints, dumpBlackPoint);
148         if (dumpResults) {
149           dumpResult(inputFile, result);
150         }
151       }
152     } else {
153       decode(new URI(argument), hints, dumpBlackPoint);
154     }
155   }
156
157   private static void dumpResult(File input, Result result) throws IOException {
158     String name = input.getAbsolutePath();
159     int pos = name.lastIndexOf('.');
160     if (pos > 0) {
161       name = name.substring(0, pos);
162     }
163     File dump = new File(name + ".txt");
164     writeStringToFile(result.getText(), dump);
165   }
166
167   private static void writeStringToFile(String value, File file) throws IOException {
168     Writer out = new OutputStreamWriter(new FileOutputStream(file), Charset.forName("UTF8"));
169     try {
170       out.write(value);
171     } finally {
172       out.close();
173     }
174   }
175
176   private static Result decode(URI uri, Hashtable<DecodeHintType, Object> hints,
177       boolean dumpBlackPoint) throws IOException {
178     BufferedImage image;
179     try {
180       image = ImageIO.read(uri.toURL());
181     } catch (IllegalArgumentException iae) {
182       throw new FileNotFoundException("Resource not found: " + uri);
183     }
184     if (image == null) {
185       System.err.println(uri.toString() + ": Could not load image");
186       return null;
187     }
188     try {
189       LuminanceSource source = new BufferedImageLuminanceSource(image);
190       BinaryBitmap bitmap = new BinaryBitmap(new GlobalHistogramBinarizer(source));
191       if (dumpBlackPoint) {
192         dumpBlackPoint(uri, image, bitmap);
193       }
194       Result result = new MultiFormatReader().decode(bitmap, hints);
195       ParsedResult parsedResult = ResultParser.parseResult(result);
196       System.out.println(uri.toString() + " (format: " + result.getBarcodeFormat() +
197           ", type: " + parsedResult.getType() + "):\nRaw result:\n" + result.getText() +
198           "\nParsed result:\n" + parsedResult.getDisplayResult());
199       return result;
200     } catch (ReaderException e) {
201       System.out.println(uri.toString() + ": No barcode found");
202       return null;
203     }
204   }
205
206   // Writes out a single PNG which is three times the width of the input image, containing from left
207   // to right: the original image, the row sampling monochrome version, and the 2D sampling
208   // monochrome version.
209   // TODO: Update to compare different Binarizer implementations.
210   private static void dumpBlackPoint(URI uri, BufferedImage image, BinaryBitmap bitmap) {
211     String inputName = uri.getPath();
212     if (inputName.contains(".mono.png")) {
213       return;
214     }
215
216     int width = bitmap.getWidth();
217     int height = bitmap.getHeight();
218     int stride = width * 3;
219     int[] pixels = new int[stride * height];
220
221     // The original image
222     int[] argb = new int[width];
223     for (int y = 0; y < height; y++) {
224       image.getRGB(0, y, width, 1, argb, 0, width);
225       System.arraycopy(argb, 0, pixels, y * stride, width);
226     }
227
228     // Row sampling
229     BitArray row = new BitArray(width);
230     for (int y = 0; y < height; y++) {
231       try {
232         row = bitmap.getBlackRow(y, row);
233       } catch (ReaderException e) {
234         // If fetching the row failed, draw a red line and keep going.
235         int offset = y * stride + width;
236         for (int x = 0; x < width; x++) {
237           pixels[offset + x] = 0xffff0000;
238         }
239         continue;
240       }
241
242       int offset = y * stride + width;
243       for (int x = 0; x < width; x++) {
244         if (row.get(x)) {
245           pixels[offset + x] = 0xff000000;
246         } else {
247           pixels[offset + x] = 0xffffffff;
248         }
249       }
250     }
251
252     // 2D sampling
253     try {
254       for (int y = 0; y < height; y++) {
255         BitMatrix matrix = bitmap.getBlackMatrix();
256         int offset = y * stride + width * 2;
257         for (int x = 0; x < width; x++) {
258           if (matrix.get(x, y)) {
259             pixels[offset + x] = 0xff000000;
260           } else {
261             pixels[offset + x] = 0xffffffff;
262           }
263         }
264       }
265     } catch (ReaderException e) {
266     }
267
268     // Write the result
269     BufferedImage result = new BufferedImage(stride, height, BufferedImage.TYPE_INT_ARGB);
270     result.setRGB(0, 0, stride, height, pixels, 0, stride);
271
272     // Use the current working directory for URLs
273     String resultName = inputName;
274     if ("http".equals(uri.getScheme())) {
275       int pos = resultName.lastIndexOf('/');
276       if (pos > 0) {
277         resultName = '.' + resultName.substring(pos);
278       }
279     }
280     int pos = resultName.lastIndexOf('.');
281     if (pos > 0) {
282       resultName = resultName.substring(0, pos);
283     }
284     resultName += ".mono.png";
285     OutputStream outStream = null;
286     try {
287       outStream = new FileOutputStream(resultName);
288       ImageIO.write(result, "png", outStream);
289     } catch (FileNotFoundException e) {
290       System.err.println("Could not create " + resultName);
291     } catch (IOException e) {
292       System.err.println("Could not write to " + resultName);
293     } finally {
294       try {
295         if (outStream != null) {
296           outStream.close();
297         }
298       } catch (IOException ioe) {
299         // continue
300       }
301     }
302   }
303
304 }