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 = isWhiteRange(row, Math.max(0, start - 2 * (startRange[1] - start)), start);
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 (!isWhiteRange(row, end, Math.min(row.getSize(), end + 2 * (end - endRange[0])))) {
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 * @return true iff row consists of white values in the range [start,end)
121 protected static boolean isWhiteRange(BitArray row, int start, int end) {
122 for (int i = start; i < end; i++) {
131 * Computes the UPC/EAN checksum on a string of digits, and reports
132 * whether the checksum is correct or not.
134 * @param s string of digits to check
135 * @return true iff string of digits passes the UPC/EAN checksum algorithm
136 * @throws ReaderException if the string does not contain only digits
138 protected boolean checkChecksum(String s) throws ReaderException {
140 int length = s.length();
141 for (int i = length - 2; i >= 0; i -= 2) {
142 int digit = (int) s.charAt(i) - (int) '0';
143 if (digit < 0 || digit > 9) {
144 throw new ReaderException("Illegal character during checksum");
149 for (int i = length - 1; i >= 0; i -= 2) {
150 int digit = (int) s.charAt(i) - (int) '0';
151 if (digit < 0 || digit > 9) {
152 throw new ReaderException("Illegal character during checksum");
156 return sum % 10 == 0;
160 * Subclasses override this to decode the portion of a barcode between the start and end guard patterns.
162 * @param row row of black/white values to search
163 * @param startRange start/end offset of start guard pattern
164 * @param resultString {@link StringBuffer} to append decoded chars to
165 * @return horizontal offset of first pixel after the "middle" that was decoded
166 * @throws ReaderException if decoding could not complete successfully
168 protected abstract int decodeMiddle(BitArray row, int[] startRange, StringBuffer resultString)
169 throws ReaderException;
171 protected int[] decodeEnd(BitArray row, int endStart) throws ReaderException {
172 return findGuardPattern(row, endStart, false, START_END_PATTERN);
176 * @param row row of black/white values to search
177 * @param rowOffset position to start search
178 * @param whiteFirst if true, indicates that the pattern specifies white/black/white/...
179 * pixel counts, otherwise, it is interpreted as black/white/black/...
180 * @param pattern pattern of counts of number of black and white pixels that are being
181 * searched for as a pattern
182 * @return start/end horizontal offset of guard pattern, as an array of two ints
183 * @throws ReaderException if pattern is not found
185 protected static int[] findGuardPattern(BitArray row, int rowOffset, boolean whiteFirst, int[] pattern)
186 throws ReaderException {
187 int patternLength = pattern.length;
188 int[] counters = new int[patternLength];
189 int width = row.getSize();
190 boolean isWhite = false;
191 while (rowOffset < width) {
192 isWhite = !row.get(rowOffset);
193 if (whiteFirst == isWhite) {
199 int counterPosition = 0;
200 int patternStart = rowOffset;
201 for (int x = rowOffset; x < width; x++) {
202 boolean pixel = row.get(x);
203 if ((!pixel && isWhite) || (pixel && !isWhite)) {
204 counters[counterPosition]++;
206 if (counterPosition == patternLength - 1) {
207 if (patternMatchVariance(counters, pattern) < MAX_VARIANCE) {
208 return new int[] {patternStart, x};
210 patternStart += counters[0] + counters[1];
211 for (int y = 2; y < patternLength; y++) {
212 counters[y - 2] = counters[y];
218 counters[counterPosition] = 1;
222 throw new ReaderException("Can't find pattern");
226 * Attempts to decode a single UPC/EAN-encoded digit.
228 * @param row row of black/white values to decode
229 * @param counters the counts of runs of observed black/white/black/... values
230 * @param rowOffset horizontal offset to start decoding from
231 * @param patterns the set of patterns to use to decode -- sometimes different encodings
232 * for the digits 0-9 are used, and this indicates the encodings for 0 to 9 that should
234 * @return horizontal offset of first pixel beyond the decoded digit
235 * @throws ReaderException if digit cannot be decoded
237 protected static int decodeDigit(BitArray row,
240 int[][] patterns) throws ReaderException {
241 recordPattern(row, rowOffset, counters);
242 float bestVariance = MAX_VARIANCE; // worst variance we'll accept
244 for (int d = 0; d < patterns.length; d++) {
245 int[] pattern = patterns[d];
246 float variance = patternMatchVariance(counters, pattern);
247 if (variance < bestVariance) {
248 bestVariance = variance;
252 if (bestMatch >= 0) {
255 throw new ReaderException("Could not match any digit in pattern");