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