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