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 javax.imageio.ImageIO;
30 import java.awt.image.BufferedImage;
32 import java.io.FileNotFoundException;
33 import java.io.FileOutputStream;
34 import java.io.IOException;
35 import java.io.OutputStream;
36 import java.io.OutputStreamWriter;
37 import java.io.Writer;
39 import java.net.URISyntaxException;
40 import java.nio.charset.Charset;
41 import java.util.Hashtable;
44 * <p>This simple command line utility decodes files, directories of files, or URIs which are passed
45 * as arguments. By default it uses the normal decoding algorithms, but you can pass --try_harder to
46 * request that hint. The raw text of each barcode is printed, and when running against directories,
47 * summary statistics are also displayed.</p>
50 * @author dswitkin@google.com (Daniel Switkin)
52 public final class CommandLineRunner {
54 private CommandLineRunner() {
57 public static void main(String[] args) throws Exception {
58 Hashtable<DecodeHintType, Object> hints = null;
59 boolean dumpResults = false;
60 boolean dumpBlackPoint = false;
61 for (String arg : args) {
62 if ("--try_harder".equals(arg)) {
63 hints = new Hashtable<DecodeHintType, Object>(3);
64 hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
65 } else if ("--dump_results".equals(arg)) {
67 } else if ("--dump_black_point".equals(arg)) {
68 dumpBlackPoint = true;
69 } else if (arg.startsWith("--")) {
70 System.out.println("Unknown command line option " + arg);
74 for (String arg : args) {
75 if (!arg.startsWith("--")) {
76 decodeOneArgument(arg, hints, dumpResults, dumpBlackPoint);
81 private static void decodeOneArgument(String argument, Hashtable<DecodeHintType, Object> hints,
82 boolean dumpResults, boolean dumpBlackPoint) throws IOException,
85 File inputFile = new File(argument);
86 if (inputFile.exists()) {
87 if (inputFile.isDirectory()) {
90 for (File input : inputFile.listFiles()) {
91 String filename = input.getName().toLowerCase();
92 // Skip hidden files and text files (the latter is found in the blackbox tests).
93 if (filename.startsWith(".") || filename.endsWith(".txt")) {
96 // Skip the results of dumping the black point.
97 if (filename.contains(".mono.png")) {
100 Result result = decode(input.toURI(), hints, dumpBlackPoint);
101 if (result != null) {
104 dumpResult(input, result);
109 System.out.println("\nDecoded " + successful + " files out of " + total +
110 " successfully (" + (successful * 100 / total) + "%)\n");
112 Result result = decode(inputFile.toURI(), hints, dumpBlackPoint);
114 dumpResult(inputFile, result);
118 decode(new URI(argument), hints, dumpBlackPoint);
122 private static void dumpResult(File input, Result result) throws IOException {
123 String name = input.getAbsolutePath();
124 int pos = name.lastIndexOf('.');
126 name = name.substring(0, pos);
128 File dump = new File(name + ".txt");
129 writeStringToFile(result.getText(), dump);
132 private static void writeStringToFile(String value, File file) throws IOException {
133 Writer out = new OutputStreamWriter(new FileOutputStream(file), Charset.forName("UTF8"));
141 private static Result decode(URI uri, Hashtable<DecodeHintType, Object> hints,
142 boolean dumpBlackPoint) throws IOException {
145 image = ImageIO.read(uri.toURL());
146 } catch (IllegalArgumentException iae) {
147 throw new FileNotFoundException("Resource not found: " + uri);
150 System.err.println(uri.toString() + ": Could not load image");
154 MonochromeBitmapSource source = new BufferedImageMonochromeBitmapSource(image);
155 if (dumpBlackPoint) {
156 dumpBlackPoint(uri, image, source);
158 Result result = new MultiFormatReader().decode(source, hints);
159 ParsedResult parsedResult = ResultParser.parseResult(result);
160 System.out.println(uri.toString() + " (format: " + result.getBarcodeFormat() +
161 ", type: " + parsedResult.getType() + "):\nRaw result:\n" + result.getText() +
162 "\nParsed result:\n" + parsedResult.getDisplayResult());
164 } catch (ReaderException e) {
165 System.out.println(uri.toString() + ": No barcode found");
170 // Writes out a single PNG which is three times the width of the input image, containing from left
171 // to right: the original image, the row sampling monochrome version, and the 2D sampling
172 // monochrome version.
173 private static void dumpBlackPoint(URI uri, BufferedImage image, MonochromeBitmapSource source) {
174 String inputName = uri.getPath();
175 if (inputName.contains(".mono.png")) {
179 int width = source.getWidth();
180 int height = source.getHeight();
181 int stride = width * 3;
182 int[] pixels = new int[stride * height];
184 // The original image
185 int[] argb = new int[width];
186 for (int y = 0; y < height; y++) {
187 image.getRGB(0, y, width, 1, argb, 0, width);
188 System.arraycopy(argb, 0, pixels, y * stride, width);
193 BitArray row = new BitArray(width);
194 for (int y = 0; y < height; y++) {
196 source.estimateBlackPoint(BlackPointEstimationMethod.ROW_SAMPLING, y);
197 } catch (ReaderException e) {
198 // If the row histogram failed, draw a red line and keep going
199 int offset = y * stride + width;
200 for (int x = 0; x < width; x++) {
201 pixels[offset + x] = 0xffff0000;
205 source.getBlackRow(y, row, 0, width);
206 int offset = y * stride + width;
207 for (int x = 0; x < width; x++) {
209 pixels[offset + x] = 0xff000000;
211 pixels[offset + x] = 0xffffffff;
218 source.estimateBlackPoint(BlackPointEstimationMethod.TWO_D_SAMPLING, 0);
219 for (int y = 0; y < height; y++) {
220 source.getBlackRow(y, row, 0, width);
221 int offset = y * stride + width * 2;
222 for (int x = 0; x < width; x++) {
224 pixels[offset + x] = 0xff000000;
226 pixels[offset + x] = 0xffffffff;
230 } catch (ReaderException e) {
234 BufferedImage result = new BufferedImage(stride, height, BufferedImage.TYPE_INT_ARGB);
235 result.setRGB(0, 0, stride, height, pixels, 0, stride);
237 // Use the current working directory for URLs
238 String resultName = inputName;
239 if (uri.getScheme().equals("http")) {
240 int pos = resultName.lastIndexOf('/');
242 resultName = "." + resultName.substring(pos);
245 int pos = resultName.lastIndexOf('.');
247 resultName = resultName.substring(0, pos);
249 resultName += ".mono.png";
251 OutputStream outStream = new FileOutputStream(resultName);
252 ImageIO.write(result, "png", outStream);
253 } catch (FileNotFoundException e) {
254 System.out.println("Could not create " + resultName);
255 } catch (IOException e) {
256 System.out.println("Could not write to " + resultName);