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) {
67 Hashtable<DecodeHintType, Object> hints = buildHints();
68 boolean dumpResults = false;
69 boolean dumpBlackPoint = false;
70 for (String arg : args) {
71 if ("--try_harder".equals(arg)) {
72 hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
73 } else if ("--dump_results".equals(arg)) {
75 } else if ("--dump_black_point".equals(arg)) {
76 dumpBlackPoint = true;
77 } else if (arg.startsWith("-")) {
78 System.err.println("Unknown command line option " + arg);
83 for (String arg : args) {
84 if (!arg.startsWith("--")) {
85 decodeOneArgument(arg, hints, dumpResults, dumpBlackPoint);
90 // Manually turn on all formats, even those not yet considered production quality.
91 private static Hashtable<DecodeHintType, Object> buildHints() {
92 Hashtable<DecodeHintType, Object> hints = new Hashtable<DecodeHintType, Object>(3);
93 Vector<BarcodeFormat> vector = new Vector<BarcodeFormat>(8);
94 vector.addElement(BarcodeFormat.UPC_A);
95 vector.addElement(BarcodeFormat.UPC_E);
96 vector.addElement(BarcodeFormat.EAN_13);
97 vector.addElement(BarcodeFormat.EAN_8);
98 vector.addElement(BarcodeFormat.CODE_39);
99 vector.addElement(BarcodeFormat.CODE_128);
100 vector.addElement(BarcodeFormat.ITF);
101 vector.addElement(BarcodeFormat.QR_CODE);
102 vector.addElement(BarcodeFormat.DATAMATRIX);
103 vector.addElement(BarcodeFormat.PDF417);
104 hints.put(DecodeHintType.POSSIBLE_FORMATS, vector);
108 private static void printUsage() {
109 System.err.println("Decode barcode images using the ZXing library\n");
110 System.err.println("usage: CommandLineRunner { file | dir | url } [ options ]");
111 System.err.println(" --try_harder: Use the TRY_HARDER hint, default is normal (mobile) mode");
112 System.err.println(" --dump_results: Write the decoded contents to input.txt");
113 System.err.println(" --dump_black_point: Compare black point algorithms as input.mono.png");
116 private static void decodeOneArgument(String argument, Hashtable<DecodeHintType, Object> hints,
117 boolean dumpResults, boolean dumpBlackPoint) throws IOException,
120 File inputFile = new File(argument);
121 if (inputFile.exists()) {
122 if (inputFile.isDirectory()) {
125 for (File input : inputFile.listFiles()) {
126 String filename = input.getName().toLowerCase();
127 // Skip hidden files and text files (the latter is found in the blackbox tests).
128 if (filename.startsWith(".") || filename.endsWith(".txt")) {
131 // Skip the results of dumping the black point.
132 if (filename.contains(".mono.png")) {
135 Result result = decode(input.toURI(), hints, dumpBlackPoint);
136 if (result != null) {
139 dumpResult(input, result);
144 System.out.println("\nDecoded " + successful + " files out of " + total +
145 " successfully (" + (successful * 100 / total) + "%)\n");
147 Result result = decode(inputFile.toURI(), hints, dumpBlackPoint);
149 dumpResult(inputFile, result);
153 decode(new URI(argument), hints, dumpBlackPoint);
157 private static void dumpResult(File input, Result result) throws IOException {
158 String name = input.getAbsolutePath();
159 int pos = name.lastIndexOf('.');
161 name = name.substring(0, pos);
163 File dump = new File(name + ".txt");
164 writeStringToFile(result.getText(), dump);
167 private static void writeStringToFile(String value, File file) throws IOException {
168 Writer out = new OutputStreamWriter(new FileOutputStream(file), Charset.forName("UTF8"));
176 private static Result decode(URI uri, Hashtable<DecodeHintType, Object> hints,
177 boolean dumpBlackPoint) throws IOException {
180 image = ImageIO.read(uri.toURL());
181 } catch (IllegalArgumentException iae) {
182 throw new FileNotFoundException("Resource not found: " + uri);
185 System.err.println(uri.toString() + ": Could not load image");
189 LuminanceSource source = new BufferedImageLuminanceSource(image);
190 BinaryBitmap bitmap = new BinaryBitmap(new GlobalHistogramBinarizer(source));
191 if (dumpBlackPoint) {
192 dumpBlackPoint(uri, image, bitmap);
194 Result result = new MultiFormatReader().decode(bitmap, hints);
195 ParsedResult parsedResult = ResultParser.parseResult(result);
196 System.out.println(uri.toString() + " (format: " + result.getBarcodeFormat() +
197 ", type: " + parsedResult.getType() + "):\nRaw result:\n" + result.getText() +
198 "\nParsed result:\n" + parsedResult.getDisplayResult());
200 } catch (ReaderException e) {
201 System.out.println(uri.toString() + ": No barcode found");
206 // Writes out a single PNG which is three times the width of the input image, containing from left
207 // to right: the original image, the row sampling monochrome version, and the 2D sampling
208 // monochrome version.
209 // TODO: Update to compare different Binarizer implementations.
210 private static void dumpBlackPoint(URI uri, BufferedImage image, BinaryBitmap bitmap) {
211 String inputName = uri.getPath();
212 if (inputName.contains(".mono.png")) {
216 int width = bitmap.getWidth();
217 int height = bitmap.getHeight();
218 int stride = width * 3;
219 int[] pixels = new int[stride * height];
221 // The original image
222 int[] argb = new int[width];
223 for (int y = 0; y < height; y++) {
224 image.getRGB(0, y, width, 1, argb, 0, width);
225 System.arraycopy(argb, 0, pixels, y * stride, width);
229 BitArray row = new BitArray(width);
230 for (int y = 0; y < height; y++) {
232 row = bitmap.getBlackRow(y, row);
233 } catch (ReaderException e) {
234 // If fetching the row failed, draw a red line and keep going.
235 int offset = y * stride + width;
236 for (int x = 0; x < width; x++) {
237 pixels[offset + x] = 0xffff0000;
242 int offset = y * stride + width;
243 for (int x = 0; x < width; x++) {
245 pixels[offset + x] = 0xff000000;
247 pixels[offset + x] = 0xffffffff;
254 for (int y = 0; y < height; y++) {
255 BitMatrix matrix = bitmap.getBlackMatrix();
256 int offset = y * stride + width * 2;
257 for (int x = 0; x < width; x++) {
258 if (matrix.get(x, y)) {
259 pixels[offset + x] = 0xff000000;
261 pixels[offset + x] = 0xffffffff;
265 } catch (ReaderException e) {
269 BufferedImage result = new BufferedImage(stride, height, BufferedImage.TYPE_INT_ARGB);
270 result.setRGB(0, 0, stride, height, pixels, 0, stride);
272 // Use the current working directory for URLs
273 String resultName = inputName;
274 if ("http".equals(uri.getScheme())) {
275 int pos = resultName.lastIndexOf('/');
277 resultName = '.' + resultName.substring(pos);
280 int pos = resultName.lastIndexOf('.');
282 resultName = resultName.substring(0, pos);
284 resultName += ".mono.png";
285 OutputStream outStream = null;
287 outStream = new FileOutputStream(resultName);
288 ImageIO.write(result, "png", outStream);
289 } catch (FileNotFoundException e) {
290 System.err.println("Could not create " + resultName);
291 } catch (IOException e) {
292 System.err.println("Could not write to " + resultName);
295 if (outStream != null) {
298 } catch (IOException ioe) {