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.Result;
20 import com.google.zxing.ResultPoint;
21 import com.google.zxing.ReaderException;
22 import com.google.zxing.common.BitArray;
23 import com.google.zxing.common.GenericResultPoint;
26 * <p>Encapsulates functionality and implementation that is common to UPC and EAN families
27 * of one-dimensional barcodes.</p>
29 * @author dswitkin@google.com (Daniel Switkin)
30 * @author srowen@google.com (Sean Owen)
31 * @author alasdair@google.com (Alasdair Mackintosh)
33 public abstract class AbstractUPCEANReader extends AbstractOneDReader implements UPCEANReader {
35 private static final float MAX_VARIANCE = 0.4f;
37 /** Start/end guard pattern. */
38 protected static final int[] START_END_PATTERN = {1, 1, 1,};
40 /** Pattern marking the middle of a UPC/EAN pattern, separating the two halves. */
41 protected static final int[] MIDDLE_PATTERN = {1, 1, 1, 1, 1};
43 /** "Odd", or "L" patterns used to encode UPC/EAN digits. */
44 protected static final int[][] L_PATTERNS = {
57 /** As above but also including the "even", or "G" patterns used to encode UPC/EAN digits. */
58 protected static final int[][] L_AND_G_PATTERNS;
61 L_AND_G_PATTERNS = new int[20][];
62 for (int i = 0; i < 10; i++) {
63 L_AND_G_PATTERNS[i] = L_PATTERNS[i];
65 for (int i = 10; i < 20; i++) {
66 int[] widths = L_PATTERNS[i - 10];
67 int[] reversedWidths = new int[widths.length];
68 for (int j = 0; j < widths.length; j++) {
69 reversedWidths[j] = widths[widths.length - j - 1];
71 L_AND_G_PATTERNS[i] = reversedWidths;
75 static int[] findStartGuardPattern(final BitArray row) throws ReaderException {
76 boolean foundStart = false;
77 int[] startRange = null;
80 startRange = findGuardPattern(row, nextStart, false, START_END_PATTERN);
81 int start = startRange[0];
82 nextStart = startRange[1];
83 // As a check, we want to see some white in front of this "start pattern",
84 // maybe as wide as the start pattern itself?
85 foundStart = row.isRange(Math.max(0, start - 2 * (startRange[1] - start)), start, false);
90 public final Result decodeRow(int rowNumber, BitArray row) throws ReaderException {
91 return decodeRow(rowNumber, row, findStartGuardPattern(row));
94 public final Result decodeRow(int rowNumber, BitArray row, int[] startGuardRange) throws ReaderException {
96 StringBuffer result = new StringBuffer();
98 int endStart = decodeMiddle(row, startGuardRange, result);
100 int[] endRange = decodeEnd(row, endStart);
102 // Check for whitespace after the pattern
103 int end = endRange[1];
104 if (!row.isRange(end, Math.min(row.getSize(), end + 2 * (end - endRange[0])), false)) {
105 throw new ReaderException("Pattern not followed by whitespace");
108 String resultString = result.toString();
109 if (!checkChecksum(resultString)) {
110 throw new ReaderException("Checksum failed");
113 return new Result(resultString, new ResultPoint[]{
114 new GenericResultPoint((float) (startGuardRange[1] - startGuardRange[0]) / 2.0f, (float) rowNumber),
115 new GenericResultPoint((float) (endRange[1] - endRange[0]) / 2.0f, (float) rowNumber)});
119 * Computes the UPC/EAN checksum on a string of digits, and reports
120 * whether the checksum is correct or not.
122 * @param s string of digits to check
123 * @return true iff string of digits passes the UPC/EAN checksum algorithm
124 * @throws ReaderException if the string does not contain only digits
126 protected boolean checkChecksum(String s) throws ReaderException {
128 int length = s.length();
129 for (int i = length - 2; i >= 0; i -= 2) {
130 int digit = (int) s.charAt(i) - (int) '0';
131 if (digit < 0 || digit > 9) {
132 throw new ReaderException("Illegal character during checksum");
137 for (int i = length - 1; i >= 0; i -= 2) {
138 int digit = (int) s.charAt(i) - (int) '0';
139 if (digit < 0 || digit > 9) {
140 throw new ReaderException("Illegal character during checksum");
144 return sum % 10 == 0;
148 * Subclasses override this to decode the portion of a barcode between the start and end guard patterns.
150 * @param row row of black/white values to search
151 * @param startRange start/end offset of start guard pattern
152 * @param resultString {@link StringBuffer} to append decoded chars to
153 * @return horizontal offset of first pixel after the "middle" that was decoded
154 * @throws ReaderException if decoding could not complete successfully
156 protected abstract int decodeMiddle(BitArray row, int[] startRange, StringBuffer resultString)
157 throws ReaderException;
159 protected int[] decodeEnd(BitArray row, int endStart) throws ReaderException {
160 return findGuardPattern(row, endStart, false, START_END_PATTERN);
164 * @param row row of black/white values to search
165 * @param rowOffset position to start search
166 * @param whiteFirst if true, indicates that the pattern specifies white/black/white/...
167 * pixel counts, otherwise, it is interpreted as black/white/black/...
168 * @param pattern pattern of counts of number of black and white pixels that are being
169 * searched for as a pattern
170 * @return start/end horizontal offset of guard pattern, as an array of two ints
171 * @throws ReaderException if pattern is not found
173 protected static int[] findGuardPattern(BitArray row, int rowOffset, boolean whiteFirst, int[] pattern)
174 throws ReaderException {
175 int patternLength = pattern.length;
176 int[] counters = new int[patternLength];
177 int width = row.getSize();
178 boolean isWhite = false;
179 while (rowOffset < width) {
180 isWhite = !row.get(rowOffset);
181 if (whiteFirst == isWhite) {
187 int counterPosition = 0;
188 int patternStart = rowOffset;
189 for (int x = rowOffset; x < width; x++) {
190 boolean pixel = row.get(x);
191 if ((!pixel && isWhite) || (pixel && !isWhite)) {
192 counters[counterPosition]++;
194 if (counterPosition == patternLength - 1) {
195 if (patternMatchVariance(counters, pattern) < MAX_VARIANCE) {
196 return new int[] {patternStart, x};
198 patternStart += counters[0] + counters[1];
199 for (int y = 2; y < patternLength; y++) {
200 counters[y - 2] = counters[y];
206 counters[counterPosition] = 1;
210 throw new ReaderException("Can't find pattern");
214 * Attempts to decode a single UPC/EAN-encoded digit.
216 * @param row row of black/white values to decode
217 * @param counters the counts of runs of observed black/white/black/... values
218 * @param rowOffset horizontal offset to start decoding from
219 * @param patterns the set of patterns to use to decode -- sometimes different encodings
220 * for the digits 0-9 are used, and this indicates the encodings for 0 to 9 that should
222 * @return horizontal offset of first pixel beyond the decoded digit
223 * @throws ReaderException if digit cannot be decoded
225 protected static int decodeDigit(BitArray row,
228 int[][] patterns) throws ReaderException {
229 recordPattern(row, rowOffset, counters);
230 float bestVariance = MAX_VARIANCE; // worst variance we'll accept
232 for (int d = 0; d < patterns.length; d++) {
233 int[] pattern = patterns[d];
234 float variance = patternMatchVariance(counters, pattern);
235 if (variance < bestVariance) {
236 bestVariance = variance;
240 if (bestMatch >= 0) {
243 throw new ReaderException("Could not match any digit in pattern");