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.BlackPointEstimationMethod;
20 import com.google.zxing.DecodeHintType;
21 import com.google.zxing.MonochromeBitmapSource;
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;
29 import java.awt.image.BufferedImage;
31 import java.io.FileNotFoundException;
32 import java.io.FileOutputStream;
33 import java.io.IOException;
34 import java.io.OutputStream;
35 import java.io.OutputStreamWriter;
36 import java.io.Writer;
38 import java.net.URISyntaxException;
39 import java.nio.charset.Charset;
40 import java.util.Hashtable;
42 import javax.imageio.ImageIO;
45 * <p>This simple command line utility decodes files, directories of files, or URIs which are passed
46 * as arguments. By default it uses the normal decoding algorithms, but you can pass --try_harder to
47 * request that hint. The raw text of each barcode is printed, and when running against directories,
48 * summary statistics are also displayed.</p>
51 * @author dswitkin@google.com (Daniel Switkin)
53 public final class CommandLineRunner {
55 private CommandLineRunner() {
58 public static void main(String[] args) throws Exception {
59 if (args == null || args.length == 0) {
63 Hashtable<DecodeHintType, Object> hints = null;
64 boolean dumpResults = false;
65 boolean dumpBlackPoint = false;
66 for (String arg : args) {
67 if ("--try_harder".equals(arg)) {
68 hints = new Hashtable<DecodeHintType, Object>(3);
69 hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
70 } else if ("--dump_results".equals(arg)) {
72 } else if ("--dump_black_point".equals(arg)) {
73 dumpBlackPoint = true;
74 } else if (arg.startsWith("-")) {
75 System.out.println("Unknown command line option " + arg);
80 for (String arg : args) {
81 if (!arg.startsWith("--")) {
82 decodeOneArgument(arg, hints, dumpResults, dumpBlackPoint);
87 private static void printUsage() {
88 System.out.println("Decode barcode images using the ZXing library\n");
89 System.out.println("usage: CommandLineRunner { file | dir | url } [ options ]");
90 System.out.println(" --try_harder: Use the TRY_HARDER hint, default is normal (mobile) mode");
91 System.out.println(" --dump_results: Write the decoded contents to input.txt");
92 System.out.println(" --dump_black_point: Compare black point algorithms as input.mono.png");
95 private static void decodeOneArgument(String argument, Hashtable<DecodeHintType, Object> hints,
96 boolean dumpResults, boolean dumpBlackPoint) throws IOException,
99 File inputFile = new File(argument);
100 if (inputFile.exists()) {
101 if (inputFile.isDirectory()) {
104 for (File input : inputFile.listFiles()) {
105 String filename = input.getName().toLowerCase();
106 // Skip hidden files and text files (the latter is found in the blackbox tests).
107 if (filename.startsWith(".") || filename.endsWith(".txt")) {
110 // Skip the results of dumping the black point.
111 if (filename.contains(".mono.png")) {
114 Result result = decode(input.toURI(), hints, dumpBlackPoint);
115 if (result != null) {
118 dumpResult(input, result);
123 System.out.println("\nDecoded " + successful + " files out of " + total +
124 " successfully (" + (successful * 100 / total) + "%)\n");
126 Result result = decode(inputFile.toURI(), hints, dumpBlackPoint);
128 dumpResult(inputFile, result);
132 decode(new URI(argument), hints, dumpBlackPoint);
136 private static void dumpResult(File input, Result result) throws IOException {
137 String name = input.getAbsolutePath();
138 int pos = name.lastIndexOf('.');
140 name = name.substring(0, pos);
142 File dump = new File(name + ".txt");
143 writeStringToFile(result.getText(), dump);
146 private static void writeStringToFile(String value, File file) throws IOException {
147 Writer out = new OutputStreamWriter(new FileOutputStream(file), Charset.forName("UTF8"));
155 private static Result decode(URI uri, Hashtable<DecodeHintType, Object> hints,
156 boolean dumpBlackPoint) throws IOException {
159 image = ImageIO.read(uri.toURL());
160 } catch (IllegalArgumentException iae) {
161 throw new FileNotFoundException("Resource not found: " + uri);
164 System.err.println(uri.toString() + ": Could not load image");
168 MonochromeBitmapSource source = new BufferedImageMonochromeBitmapSource(image);
169 if (dumpBlackPoint) {
170 dumpBlackPoint(uri, image, source);
172 Result result = new MultiFormatReader().decode(source, hints);
173 ParsedResult parsedResult = ResultParser.parseResult(result);
174 System.out.println(uri.toString() + " (format: " + result.getBarcodeFormat() +
175 ", type: " + parsedResult.getType() + "):\nRaw result:\n" + result.getText() +
176 "\nParsed result:\n" + parsedResult.getDisplayResult());
178 } catch (ReaderException e) {
179 System.out.println(uri.toString() + ": No barcode found");
184 // Writes out a single PNG which is three times the width of the input image, containing from left
185 // to right: the original image, the row sampling monochrome version, and the 2D sampling
186 // monochrome version.
187 private static void dumpBlackPoint(URI uri, BufferedImage image, MonochromeBitmapSource source) {
188 String inputName = uri.getPath();
189 if (inputName.contains(".mono.png")) {
193 int width = source.getWidth();
194 int height = source.getHeight();
195 int stride = width * 3;
196 int[] pixels = new int[stride * height];
198 // The original image
199 int[] argb = new int[width];
200 for (int y = 0; y < height; y++) {
201 image.getRGB(0, y, width, 1, argb, 0, width);
202 System.arraycopy(argb, 0, pixels, y * stride, width);
207 BitArray row = new BitArray(width);
208 for (int y = 0; y < height; y++) {
210 source.estimateBlackPoint(BlackPointEstimationMethod.ROW_SAMPLING, y);
211 } catch (ReaderException e) {
212 // If the row histogram failed, draw a red line and keep going
213 int offset = y * stride + width;
214 for (int x = 0; x < width; x++) {
215 pixels[offset + x] = 0xffff0000;
219 row = source.getBlackRow(y, row, 0, width);
220 int offset = y * stride + width;
221 for (int x = 0; x < width; x++) {
223 pixels[offset + x] = 0xff000000;
225 pixels[offset + x] = 0xffffffff;
232 source.estimateBlackPoint(BlackPointEstimationMethod.TWO_D_SAMPLING, 0);
233 for (int y = 0; y < height; y++) {
234 row = source.getBlackRow(y, row, 0, width);
235 int offset = y * stride + width * 2;
236 for (int x = 0; x < width; x++) {
238 pixels[offset + x] = 0xff000000;
240 pixels[offset + x] = 0xffffffff;
244 } catch (ReaderException e) {
248 BufferedImage result = new BufferedImage(stride, height, BufferedImage.TYPE_INT_ARGB);
249 result.setRGB(0, 0, stride, height, pixels, 0, stride);
251 // Use the current working directory for URLs
252 String resultName = inputName;
253 if (uri.getScheme().equals("http")) {
254 int pos = resultName.lastIndexOf('/');
256 resultName = "." + resultName.substring(pos);
259 int pos = resultName.lastIndexOf('.');
261 resultName = resultName.substring(0, pos);
263 resultName += ".mono.png";
265 OutputStream outStream = new FileOutputStream(resultName);
266 ImageIO.write(result, "png", outStream);
267 } catch (FileNotFoundException e) {
268 System.out.println("Could not create " + resultName);
269 } catch (IOException e) {
270 System.out.println("Could not write to " + resultName);