2 * Copyright 2007 ZXing authors
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package com.google.zxing.client.j2se;
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.BarcodeFormat;
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.GlobalHistogramBinarizer;
32 import java.awt.image.BufferedImage;
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;
41 import java.net.URISyntaxException;
42 import java.nio.charset.Charset;
43 import java.util.Hashtable;
44 import java.util.Vector;
46 import javax.imageio.ImageIO;
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>
55 * @author dswitkin@google.com (Daniel Switkin)
57 public final class CommandLineRunner {
59 private CommandLineRunner() {
62 public static void main(String[] args) throws Exception {
63 if (args == null || args.length == 0) {
68 boolean tryHarder = false;
69 boolean productsOnly = false;
70 boolean dumpResults = false;
71 boolean dumpBlackPoint = false;
72 for (String arg : args) {
73 if ("--try_harder".equals(arg)) {
75 } else if ("--products_only".equals(arg)) {
77 } else if ("--dump_results".equals(arg)) {
79 } else if ("--dump_black_point".equals(arg)) {
80 dumpBlackPoint = true;
81 } else if (arg.startsWith("-")) {
82 System.err.println("Unknown command line option " + arg);
88 Hashtable<DecodeHintType, Object> hints = buildHints(tryHarder, productsOnly);
89 for (String arg : args) {
90 if (!arg.startsWith("--")) {
91 decodeOneArgument(arg, hints, dumpResults, dumpBlackPoint);
96 // Manually turn on all formats, even those not yet considered production quality.
97 private static Hashtable<DecodeHintType, Object> buildHints(boolean tryHarder,
98 boolean productsOnly) {
99 Hashtable<DecodeHintType, Object> hints = new Hashtable<DecodeHintType, Object>(3);
100 Vector<BarcodeFormat> vector = new Vector<BarcodeFormat>(8);
101 vector.addElement(BarcodeFormat.UPC_A);
102 vector.addElement(BarcodeFormat.UPC_E);
103 vector.addElement(BarcodeFormat.EAN_13);
104 vector.addElement(BarcodeFormat.EAN_8);
106 vector.addElement(BarcodeFormat.CODE_39);
107 vector.addElement(BarcodeFormat.CODE_128);
108 vector.addElement(BarcodeFormat.ITF);
109 vector.addElement(BarcodeFormat.QR_CODE);
110 vector.addElement(BarcodeFormat.DATAMATRIX);
111 vector.addElement(BarcodeFormat.PDF417);
113 hints.put(DecodeHintType.POSSIBLE_FORMATS, vector);
115 hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
120 private static void printUsage() {
121 System.err.println("Decode barcode images using the ZXing library\n");
122 System.err.println("usage: CommandLineRunner { file | dir | url } [ options ]");
123 System.err.println(" --try_harder: Use the TRY_HARDER hint, default is normal (mobile) mode");
124 System.err.println(" --products_only: Only decode the UPC and EAN families of barcodes");
125 System.err.println(" --dump_results: Write the decoded contents to input.txt");
126 System.err.println(" --dump_black_point: Compare black point algorithms as input.mono.png");
129 private static void decodeOneArgument(String argument, Hashtable<DecodeHintType, Object> hints,
130 boolean dumpResults, boolean dumpBlackPoint) throws IOException,
133 File inputFile = new File(argument);
134 if (inputFile.exists()) {
135 if (inputFile.isDirectory()) {
138 for (File input : inputFile.listFiles()) {
139 String filename = input.getName().toLowerCase();
140 // Skip hidden files and text files (the latter is found in the blackbox tests).
141 if (filename.startsWith(".") || filename.endsWith(".txt")) {
144 // Skip the results of dumping the black point.
145 if (filename.contains(".mono.png")) {
148 Result result = decode(input.toURI(), hints, dumpBlackPoint);
149 if (result != null) {
152 dumpResult(input, result);
157 System.out.println("\nDecoded " + successful + " files out of " + total +
158 " successfully (" + (successful * 100 / total) + "%)\n");
160 Result result = decode(inputFile.toURI(), hints, dumpBlackPoint);
162 dumpResult(inputFile, result);
166 decode(new URI(argument), hints, dumpBlackPoint);
170 private static void dumpResult(File input, Result result) throws IOException {
171 String name = input.getAbsolutePath();
172 int pos = name.lastIndexOf('.');
174 name = name.substring(0, pos);
176 File dump = new File(name + ".txt");
177 writeStringToFile(result.getText(), dump);
180 private static void writeStringToFile(String value, File file) throws IOException {
181 Writer out = new OutputStreamWriter(new FileOutputStream(file), Charset.forName("UTF8"));
189 private static Result decode(URI uri, Hashtable<DecodeHintType, Object> hints,
190 boolean dumpBlackPoint) throws IOException {
193 image = ImageIO.read(uri.toURL());
194 } catch (IllegalArgumentException iae) {
195 throw new FileNotFoundException("Resource not found: " + uri);
198 System.err.println(uri.toString() + ": Could not load image");
202 LuminanceSource source = new BufferedImageLuminanceSource(image);
203 BinaryBitmap bitmap = new BinaryBitmap(new GlobalHistogramBinarizer(source));
204 if (dumpBlackPoint) {
205 dumpBlackPoint(uri, image, bitmap);
207 Result result = new MultiFormatReader().decode(bitmap, hints);
208 ParsedResult parsedResult = ResultParser.parseResult(result);
209 System.out.println(uri.toString() + " (format: " + result.getBarcodeFormat() +
210 ", type: " + parsedResult.getType() + "):\nRaw result:\n" + result.getText() +
211 "\nParsed result:\n" + parsedResult.getDisplayResult());
213 } catch (ReaderException e) {
214 System.out.println(uri.toString() + ": No barcode found");
217 // Uncomment these lines when turning on exception tracking in ReaderException.
218 //System.out.println("Threw " + ReaderException.getExceptionCountAndReset() + " exceptions");
219 //System.out.println("Throwers:\n" + ReaderException.getThrowersAndReset());
223 // Writes out a single PNG which is three times the width of the input image, containing from left
224 // to right: the original image, the row sampling monochrome version, and the 2D sampling
225 // monochrome version.
226 // TODO: Update to compare different Binarizer implementations.
227 private static void dumpBlackPoint(URI uri, BufferedImage image, BinaryBitmap bitmap) {
228 String inputName = uri.getPath();
229 if (inputName.contains(".mono.png")) {
233 int width = bitmap.getWidth();
234 int height = bitmap.getHeight();
235 int stride = width * 3;
236 int[] pixels = new int[stride * height];
238 // The original image
239 int[] argb = new int[width];
240 for (int y = 0; y < height; y++) {
241 image.getRGB(0, y, width, 1, argb, 0, width);
242 System.arraycopy(argb, 0, pixels, y * stride, width);
246 BitArray row = new BitArray(width);
247 for (int y = 0; y < height; y++) {
249 row = bitmap.getBlackRow(y, row);
250 } catch (ReaderException e) {
251 // If fetching the row failed, draw a red line and keep going.
252 int offset = y * stride + width;
253 for (int x = 0; x < width; x++) {
254 pixels[offset + x] = 0xffff0000;
259 int offset = y * stride + width;
260 for (int x = 0; x < width; x++) {
262 pixels[offset + x] = 0xff000000;
264 pixels[offset + x] = 0xffffffff;
271 for (int y = 0; y < height; y++) {
272 BitMatrix matrix = bitmap.getBlackMatrix();
273 int offset = y * stride + width * 2;
274 for (int x = 0; x < width; x++) {
275 if (matrix.get(x, y)) {
276 pixels[offset + x] = 0xff000000;
278 pixels[offset + x] = 0xffffffff;
282 } catch (ReaderException e) {
286 BufferedImage result = new BufferedImage(stride, height, BufferedImage.TYPE_INT_ARGB);
287 result.setRGB(0, 0, stride, height, pixels, 0, stride);
289 // Use the current working directory for URLs
290 String resultName = inputName;
291 if ("http".equals(uri.getScheme())) {
292 int pos = resultName.lastIndexOf('/');
294 resultName = '.' + resultName.substring(pos);
297 int pos = resultName.lastIndexOf('.');
299 resultName = resultName.substring(0, pos);
301 resultName += ".mono.png";
302 OutputStream outStream = null;
304 outStream = new FileOutputStream(resultName);
305 ImageIO.write(result, "png", outStream);
306 } catch (FileNotFoundException e) {
307 System.err.println("Could not create " + resultName);
308 } catch (IOException e) {
309 System.err.println("Could not write to " + resultName);
312 if (outStream != null) {
315 } catch (IOException ioe) {