2 * Copyright 2008 Google Inc.
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.oned;
19 import com.google.zxing.BarcodeFormat;
20 import com.google.zxing.ReaderException;
21 import com.google.zxing.Result;
22 import com.google.zxing.ResultPoint;
23 import com.google.zxing.common.BitArray;
24 import com.google.zxing.common.GenericResultPoint;
26 import java.util.Hashtable;
29 * <p>Encapsulates functionality and implementation that is common to UPC and EAN families
30 * of one-dimensional barcodes.</p>
32 * @author dswitkin@google.com (Daniel Switkin)
33 * @author srowen@google.com (Sean Owen)
34 * @author alasdair@google.com (Alasdair Mackintosh)
36 public abstract class AbstractUPCEANReader extends AbstractOneDReader implements UPCEANReader {
38 private static final int MAX_VARIANCE = 104;
41 * Start/end guard pattern.
43 private static final int[] START_END_PATTERN = {1, 1, 1,};
46 * Pattern marking the middle of a UPC/EAN pattern, separating the two halves.
48 static final int[] MIDDLE_PATTERN = {1, 1, 1, 1, 1};
51 * "Odd", or "L" patterns used to encode UPC/EAN digits.
53 static final int[][] L_PATTERNS = {
67 * As above but also including the "even", or "G" patterns used to encode UPC/EAN digits.
69 static final int[][] L_AND_G_PATTERNS;
72 L_AND_G_PATTERNS = new int[20][];
73 for (int i = 0; i < 10; i++) {
74 L_AND_G_PATTERNS[i] = L_PATTERNS[i];
76 for (int i = 10; i < 20; i++) {
77 int[] widths = L_PATTERNS[i - 10];
78 int[] reversedWidths = new int[widths.length];
79 for (int j = 0; j < widths.length; j++) {
80 reversedWidths[j] = widths[widths.length - j - 1];
82 L_AND_G_PATTERNS[i] = reversedWidths;
86 static int[] findStartGuardPattern(BitArray row) throws ReaderException {
87 boolean foundStart = false;
88 int[] startRange = null;
91 startRange = findGuardPattern(row, nextStart, false, START_END_PATTERN);
92 int start = startRange[0];
93 nextStart = startRange[1];
94 // As a check, we want to see some white in front of this "start pattern",
95 // maybe as wide as the start pattern itself?
96 foundStart = row.isRange(Math.max(0, start - 2 * (startRange[1] - start)), start, false);
101 public final Result decodeRow(int rowNumber, BitArray row, Hashtable hints) throws ReaderException {
102 return decodeRow(rowNumber, row, findStartGuardPattern(row));
105 public final Result decodeRow(int rowNumber, BitArray row, int[] startGuardRange) throws ReaderException {
106 StringBuffer result = new StringBuffer(20);
107 int endStart = decodeMiddle(row, startGuardRange, result);
108 int[] endRange = decodeEnd(row, endStart);
110 // Check for whitespace after the pattern
111 int end = endRange[1];
112 if (!row.isRange(end, Math.min(row.getSize(), end + 2 * (end - endRange[0])), false)) {
113 throw new ReaderException("Pattern not followed by whitespace");
116 String resultString = result.toString();
117 if (!checkChecksum(resultString)) {
118 throw new ReaderException("Checksum failed");
121 float left = (float) (startGuardRange[1] + startGuardRange[0]) / 2.0f;
122 float right = (float) (endRange[1] + endRange[0]) / 2.0f;
123 return new Result(resultString,
124 null, // no natural byte representation for these barcodes
126 new GenericResultPoint(left, (float) rowNumber),
127 new GenericResultPoint(right, (float) rowNumber)},
131 abstract BarcodeFormat getBarcodeFormat();
134 * Computes the UPC/EAN checksum on a string of digits, and reports
135 * whether the checksum is correct or not.
137 * @param s string of digits to check
138 * @return true iff string of digits passes the UPC/EAN checksum algorithm
139 * @throws ReaderException if the string does not contain only digits
141 boolean checkChecksum(String s) throws ReaderException {
143 int length = s.length();
144 for (int i = length - 2; i >= 0; i -= 2) {
145 int digit = (int) s.charAt(i) - (int) '0';
146 if (digit < 0 || digit > 9) {
147 throw new ReaderException("Illegal character during checksum");
152 for (int i = length - 1; i >= 0; i -= 2) {
153 int digit = (int) s.charAt(i) - (int) '0';
154 if (digit < 0 || digit > 9) {
155 throw new ReaderException("Illegal character during checksum");
159 return sum % 10 == 0;
163 * Subclasses override this to decode the portion of a barcode between the start and end guard patterns.
165 * @param row row of black/white values to search
166 * @param startRange start/end offset of start guard pattern
167 * @param resultString {@link StringBuffer} to append decoded chars to
168 * @return horizontal offset of first pixel after the "middle" that was decoded
169 * @throws ReaderException if decoding could not complete successfully
171 protected abstract int decodeMiddle(BitArray row, int[] startRange, StringBuffer resultString)
172 throws ReaderException;
174 int[] decodeEnd(BitArray row, int endStart) throws ReaderException {
175 return findGuardPattern(row, endStart, false, START_END_PATTERN);
179 * @param row row of black/white values to search
180 * @param rowOffset position to start search
181 * @param whiteFirst if true, indicates that the pattern specifies white/black/white/...
182 * pixel counts, otherwise, it is interpreted as black/white/black/...
183 * @param pattern pattern of counts of number of black and white pixels that are being
184 * searched for as a pattern
185 * @return start/end horizontal offset of guard pattern, as an array of two ints
186 * @throws ReaderException if pattern is not found
188 static int[] findGuardPattern(BitArray row, int rowOffset, boolean whiteFirst, int[] pattern)
189 throws ReaderException {
190 int patternLength = pattern.length;
191 int[] counters = new int[patternLength];
192 int width = row.getSize();
193 boolean isWhite = false;
194 while (rowOffset < width) {
195 isWhite = !row.get(rowOffset);
196 if (whiteFirst == isWhite) {
202 int counterPosition = 0;
203 int patternStart = rowOffset;
204 for (int x = rowOffset; x < width; x++) {
205 boolean pixel = row.get(x);
206 if ((!pixel && isWhite) || (pixel && !isWhite)) {
207 counters[counterPosition]++;
209 if (counterPosition == patternLength - 1) {
210 if (patternMatchVariance(counters, pattern) < MAX_VARIANCE) {
211 return new int[]{patternStart, x};
213 patternStart += counters[0] + counters[1];
214 for (int y = 2; y < patternLength; y++) {
215 counters[y - 2] = counters[y];
217 counters[patternLength - 2] = 0;
218 counters[patternLength - 1] = 0;
223 counters[counterPosition] = 1;
227 throw new ReaderException("Can't find pattern");
231 * Attempts to decode a single UPC/EAN-encoded digit.
233 * @param row row of black/white values to decode
234 * @param counters the counts of runs of observed black/white/black/... values
235 * @param rowOffset horizontal offset to start decoding from
236 * @param patterns the set of patterns to use to decode -- sometimes different encodings
237 * for the digits 0-9 are used, and this indicates the encodings for 0 to 9 that should
239 * @return horizontal offset of first pixel beyond the decoded digit
240 * @throws ReaderException if digit cannot be decoded
242 static int decodeDigit(BitArray row, int[] counters, int rowOffset, int[][] patterns)
243 throws ReaderException {
244 recordPattern(row, rowOffset, counters);
245 int bestVariance = MAX_VARIANCE; // worst variance we'll accept
247 int max = patterns.length;
248 for (int i = 0; i < max; i++) {
249 int[] pattern = patterns[i];
250 int variance = patternMatchVariance(counters, pattern);
251 if (variance < bestVariance) {
252 bestVariance = variance;
256 if (bestMatch >= 0) {
259 throw new ReaderException("Could not match any digit in pattern");