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 if (args == null || args.length == 0) {
62 Hashtable<DecodeHintType, Object> hints = null;
63 boolean dumpResults = false;
64 boolean dumpBlackPoint = false;
65 for (String arg : args) {
66 if ("--try_harder".equals(arg)) {
67 hints = new Hashtable<DecodeHintType, Object>(3);
68 hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
69 } else if ("--dump_results".equals(arg)) {
71 } else if ("--dump_black_point".equals(arg)) {
72 dumpBlackPoint = true;
73 } else if (arg.startsWith("-")) {
74 System.out.println("Unknown command line option " + arg);
79 for (String arg : args) {
80 if (!arg.startsWith("--")) {
81 decodeOneArgument(arg, hints, dumpResults, dumpBlackPoint);
86 private static void printUsage() {
87 System.out.println("Decode barcode images using the ZXing library\n");
88 System.out.println("usage: CommandLineRunner { file | dir | url } [ options ]");
89 System.out.println(" --try_harder: Use the TRY_HARDER hint, default is normal (mobile) mode");
90 System.out.println(" --dump_results: Write the decoded contents to input.txt");
91 System.out.println(" --dump_black_point: Compare black point algorithms as input.mono.png");
94 private static void decodeOneArgument(String argument, Hashtable<DecodeHintType, Object> hints,
95 boolean dumpResults, boolean dumpBlackPoint) throws IOException,
98 File inputFile = new File(argument);
99 if (inputFile.exists()) {
100 if (inputFile.isDirectory()) {
103 for (File input : inputFile.listFiles()) {
104 String filename = input.getName().toLowerCase();
105 // Skip hidden files and text files (the latter is found in the blackbox tests).
106 if (filename.startsWith(".") || filename.endsWith(".txt")) {
109 // Skip the results of dumping the black point.
110 if (filename.contains(".mono.png")) {
113 Result result = decode(input.toURI(), hints, dumpBlackPoint);
114 if (result != null) {
117 dumpResult(input, result);
122 System.out.println("\nDecoded " + successful + " files out of " + total +
123 " successfully (" + (successful * 100 / total) + "%)\n");
125 Result result = decode(inputFile.toURI(), hints, dumpBlackPoint);
127 dumpResult(inputFile, result);
131 decode(new URI(argument), hints, dumpBlackPoint);
135 private static void dumpResult(File input, Result result) throws IOException {
136 String name = input.getAbsolutePath();
137 int pos = name.lastIndexOf('.');
139 name = name.substring(0, pos);
141 File dump = new File(name + ".txt");
142 writeStringToFile(result.getText(), dump);
145 private static void writeStringToFile(String value, File file) throws IOException {
146 Writer out = new OutputStreamWriter(new FileOutputStream(file), Charset.forName("UTF8"));
154 private static Result decode(URI uri, Hashtable<DecodeHintType, Object> hints,
155 boolean dumpBlackPoint) throws IOException {
158 image = ImageIO.read(uri.toURL());
159 } catch (IllegalArgumentException iae) {
160 throw new FileNotFoundException("Resource not found: " + uri);
163 System.err.println(uri.toString() + ": Could not load image");
167 MonochromeBitmapSource source = new BufferedImageMonochromeBitmapSource(image);
168 if (dumpBlackPoint) {
169 dumpBlackPoint(uri, image, source);
171 Result result = new MultiFormatReader().decode(source, hints);
172 ParsedResult parsedResult = ResultParser.parseResult(result);
173 System.out.println(uri.toString() + " (format: " + result.getBarcodeFormat() +
174 ", type: " + parsedResult.getType() + "):\nRaw result:\n" + result.getText() +
175 "\nParsed result:\n" + parsedResult.getDisplayResult());
177 } catch (ReaderException e) {
178 System.out.println(uri.toString() + ": No barcode found");
183 // Writes out a single PNG which is three times the width of the input image, containing from left
184 // to right: the original image, the row sampling monochrome version, and the 2D sampling
185 // monochrome version.
186 private static void dumpBlackPoint(URI uri, BufferedImage image, MonochromeBitmapSource source) {
187 String inputName = uri.getPath();
188 if (inputName.contains(".mono.png")) {
192 int width = source.getWidth();
193 int height = source.getHeight();
194 int stride = width * 3;
195 int[] pixels = new int[stride * height];
197 // The original image
198 int[] argb = new int[width];
199 for (int y = 0; y < height; y++) {
200 image.getRGB(0, y, width, 1, argb, 0, width);
201 System.arraycopy(argb, 0, pixels, y * stride, width);
206 BitArray row = new BitArray(width);
207 for (int y = 0; y < height; y++) {
209 source.estimateBlackPoint(BlackPointEstimationMethod.ROW_SAMPLING, y);
210 } catch (ReaderException e) {
211 // If the row histogram failed, draw a red line and keep going
212 int offset = y * stride + width;
213 for (int x = 0; x < width; x++) {
214 pixels[offset + x] = 0xffff0000;
218 source.getBlackRow(y, row, 0, width);
219 int offset = y * stride + width;
220 for (int x = 0; x < width; x++) {
222 pixels[offset + x] = 0xff000000;
224 pixels[offset + x] = 0xffffffff;
231 source.estimateBlackPoint(BlackPointEstimationMethod.TWO_D_SAMPLING, 0);
232 for (int y = 0; y < height; y++) {
233 source.getBlackRow(y, row, 0, width);
234 int offset = y * stride + width * 2;
235 for (int x = 0; x < width; x++) {
237 pixels[offset + x] = 0xff000000;
239 pixels[offset + x] = 0xffffffff;
243 } catch (ReaderException e) {
247 BufferedImage result = new BufferedImage(stride, height, BufferedImage.TYPE_INT_ARGB);
248 result.setRGB(0, 0, stride, height, pixels, 0, stride);
250 // Use the current working directory for URLs
251 String resultName = inputName;
252 if (uri.getScheme().equals("http")) {
253 int pos = resultName.lastIndexOf('/');
255 resultName = "." + resultName.substring(pos);
258 int pos = resultName.lastIndexOf('.');
260 resultName = resultName.substring(0, pos);
262 resultName += ".mono.png";
264 OutputStream outStream = new FileOutputStream(resultName);
265 ImageIO.write(result, "png", outStream);
266 } catch (FileNotFoundException e) {
267 System.out.println("Could not create " + resultName);
268 } catch (IOException e) {
269 System.out.println("Could not write to " + resultName);