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