Added a --dump_results flag to the J2SE client, which will create a text file of...
[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.DecodeHintType;
20 import com.google.zxing.MonochromeBitmapSource;
21 import com.google.zxing.MultiFormatReader;
22 import com.google.zxing.ReaderException;
23 import com.google.zxing.Result;
24
25 import javax.imageio.ImageIO;
26 import java.awt.image.BufferedImage;
27 import java.io.File;
28 import java.io.FileNotFoundException;
29 import java.io.FileOutputStream;
30 import java.io.IOException;
31 import java.net.URI;
32 import java.util.Hashtable;
33
34 /**
35  * <p>This simple command line utility decodes files, directories of files, or URIs which are passed
36  * as arguments. By default it uses the normal decoding algorithms, but you can pass --try_harder to
37  * request that hint. The raw text of each barcode is printed, and when running against directories,
38  * summary statistics are also displayed.</p>
39  *
40  * @author srowen@google.com (Sean Owen), dswitkin@google.com (Daniel Switkin)
41  */
42 public final class CommandLineRunner {
43
44   private CommandLineRunner() {
45   }
46
47   public static void main(String[] args) throws Exception {
48     Hashtable<DecodeHintType, Object> hints = null;
49     boolean dumpResults = false;
50     for (String arg : args) {
51       if ("--try_harder".equals(arg)) {
52         hints = new Hashtable<DecodeHintType, Object>(3);
53         hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
54       } else if ("--dump_results".equals(arg)) {
55         dumpResults = true;
56       } else if (arg.startsWith("--")) {
57         System.out.println("Unknown command line option " + arg);
58         return;
59       }
60     }
61     for (String arg : args) {
62       if (!arg.startsWith("--")) {
63         decodeOneArgument(arg, hints, dumpResults);
64       }
65     }
66   }
67
68   private static void decodeOneArgument(String argument, Hashtable<DecodeHintType, Object> hints,
69       boolean dumpResults) throws Exception {
70
71     File inputFile = new File(argument);
72     if (inputFile.exists()) {
73       if (inputFile.isDirectory()) {
74         int successful = 0;
75         int total = 0;
76         for (File input : inputFile.listFiles()) {
77           String filename = input.getName().toLowerCase();
78           // Skip hidden files and text files (the latter is found in the blackbox tests).
79           if (filename.startsWith(".") || filename.endsWith(".txt")) {
80             continue;
81           }
82           Result result = decode(input.toURI(), hints);
83           if (result != null) {
84             successful++;
85             if (dumpResults) {
86               String name = input.getAbsolutePath();
87               int pos = name.lastIndexOf('.');
88               if (pos > 0) {
89                 name = name.substring(0, pos);
90               }
91               File dump = new File(name + ".txt");
92               dump.createNewFile();
93               FileOutputStream stream = new FileOutputStream(dump);
94               stream.write(result.getText().getBytes());
95               stream.close();
96             }
97           }
98           total++;
99         }
100         System.out.println("\nDecoded " + successful + " files out of " + total +
101             " successfully (" + (successful * 100 / total) + "%)\n");
102       } else {
103         decode(inputFile.toURI(), hints);
104       }
105     } else {
106       decode(new URI(argument), hints);
107     }
108   }
109
110   private static Result decode(URI uri, Hashtable<DecodeHintType, Object> hints) throws IOException {
111     BufferedImage image;
112     try {
113       image = ImageIO.read(uri.toURL());
114     } catch (IllegalArgumentException iae) {
115       throw new FileNotFoundException("Resource not found: " + uri);
116     }
117     if (image == null) {
118       System.err.println(uri.toString() + ": Could not load image");
119       return null;
120     }
121     try {
122       MonochromeBitmapSource source = new BufferedImageMonochromeBitmapSource(image);
123       Result result = new MultiFormatReader().decode(source, hints);
124       System.out.println(uri.toString() + " (format: " + result.getBarcodeFormat() + "):\n" +
125           result.getText());
126       return result;
127     } catch (ReaderException e) {
128       System.out.println(uri.toString() + ": No barcode found");
129       return null;
130     }
131   }
132
133 }