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