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.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;
31 import java.awt.image.BufferedImage;
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;
40 import java.net.URISyntaxException;
41 import java.nio.charset.Charset;
42 import java.util.Hashtable;
44 import javax.imageio.ImageIO;
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>
53 * @author dswitkin@google.com (Daniel Switkin)
55 public final class CommandLineRunner {
57 private CommandLineRunner() {
60 public static void main(String[] args) throws Exception {
61 if (args == null || args.length == 0) {
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)) {
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);
82 for (String arg : args) {
83 if (!arg.startsWith("--")) {
84 decodeOneArgument(arg, hints, dumpResults, dumpBlackPoint);
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");
97 private static void decodeOneArgument(String argument, Hashtable<DecodeHintType, Object> hints,
98 boolean dumpResults, boolean dumpBlackPoint) throws IOException,
101 File inputFile = new File(argument);
102 if (inputFile.exists()) {
103 if (inputFile.isDirectory()) {
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")) {
112 // Skip the results of dumping the black point.
113 if (filename.contains(".mono.png")) {
116 Result result = decode(input.toURI(), hints, dumpBlackPoint);
117 if (result != null) {
120 dumpResult(input, result);
125 System.out.println("\nDecoded " + successful + " files out of " + total +
126 " successfully (" + (successful * 100 / total) + "%)\n");
128 Result result = decode(inputFile.toURI(), hints, dumpBlackPoint);
130 dumpResult(inputFile, result);
134 decode(new URI(argument), hints, dumpBlackPoint);
138 private static void dumpResult(File input, Result result) throws IOException {
139 String name = input.getAbsolutePath();
140 int pos = name.lastIndexOf('.');
142 name = name.substring(0, pos);
144 File dump = new File(name + ".txt");
145 writeStringToFile(result.getText(), dump);
148 private static void writeStringToFile(String value, File file) throws IOException {
149 Writer out = new OutputStreamWriter(new FileOutputStream(file), Charset.forName("UTF8"));
157 private static Result decode(URI uri, Hashtable<DecodeHintType, Object> hints,
158 boolean dumpBlackPoint) throws IOException {
161 image = ImageIO.read(uri.toURL());
162 } catch (IllegalArgumentException iae) {
163 throw new FileNotFoundException("Resource not found: " + uri);
166 System.err.println(uri.toString() + ": Could not load image");
170 LuminanceSource source = new BufferedImageLuminanceSource(image);
171 BinaryBitmap bitmap = new BinaryBitmap(new GlobalHistogramBinarizer(source));
172 if (dumpBlackPoint) {
173 dumpBlackPoint(uri, image, bitmap);
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());
181 } catch (ReaderException e) {
182 System.out.println(uri.toString() + ": No barcode found");
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")) {
197 int width = bitmap.getWidth();
198 int height = bitmap.getHeight();
199 int stride = width * 3;
200 int[] pixels = new int[stride * height];
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);
211 BitArray row = new BitArray(width);
212 for (int y = 0; y < height; y++) {
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;
224 int offset = y * stride + width;
225 for (int x = 0; x < width; x++) {
227 pixels[offset + x] = 0xff000000;
229 pixels[offset + x] = 0xffffffff;
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;
243 pixels[offset + x] = 0xffffffff;
247 } catch (ReaderException e) {
251 BufferedImage result = new BufferedImage(stride, height, BufferedImage.TYPE_INT_ARGB);
252 result.setRGB(0, 0, stride, height, pixels, 0, stride);
254 // Use the current working directory for URLs
255 String resultName = inputName;
256 if (uri.getScheme().equals("http")) {
257 int pos = resultName.lastIndexOf('/');
259 resultName = "." + resultName.substring(pos);
262 int pos = resultName.lastIndexOf('.');
264 resultName = resultName.substring(0, pos);
266 resultName += ".mono.png";
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);