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.ReaderException;
20 import com.google.zxing.Result;
21 import com.google.zxing.ResultPoint;
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;
38 * Start/end guard pattern.
40 protected static final int[] START_END_PATTERN = {1, 1, 1,};
43 * Pattern marking the middle of a UPC/EAN pattern, separating the two halves.
45 protected static final int[] MIDDLE_PATTERN = {1, 1, 1, 1, 1};
48 * "Odd", or "L" patterns used to encode UPC/EAN digits.
50 protected static final int[][] L_PATTERNS = {
64 * As above but also including the "even", or "G" patterns used to encode UPC/EAN digits.
66 protected static final int[][] L_AND_G_PATTERNS;
69 L_AND_G_PATTERNS = new int[20][];
70 for (int i = 0; i < 10; i++) {
71 L_AND_G_PATTERNS[i] = L_PATTERNS[i];
73 for (int i = 10; i < 20; i++) {
74 int[] widths = L_PATTERNS[i - 10];
75 int[] reversedWidths = new int[widths.length];
76 for (int j = 0; j < widths.length; j++) {
77 reversedWidths[j] = widths[widths.length - j - 1];
79 L_AND_G_PATTERNS[i] = reversedWidths;
83 static int[] findStartGuardPattern(final BitArray row) throws ReaderException {
84 boolean foundStart = false;
85 int[] startRange = null;
88 startRange = findGuardPattern(row, nextStart, false, START_END_PATTERN);
89 int start = startRange[0];
90 nextStart = startRange[1];
91 // As a check, we want to see some white in front of this "start pattern",
92 // maybe as wide as the start pattern itself?
93 foundStart = row.isRange(Math.max(0, start - 2 * (startRange[1] - start)), start, false);
98 public final Result decodeRow(int rowNumber, BitArray row) throws ReaderException {
99 return decodeRow(rowNumber, row, findStartGuardPattern(row));
102 public final Result decodeRow(int rowNumber, BitArray row, int[] startGuardRange) throws ReaderException {
104 StringBuffer result = new StringBuffer();
106 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 return new Result(resultString, new ResultPoint[]{
122 new GenericResultPoint((float) (startGuardRange[1] - startGuardRange[0]) / 2.0f, (float) rowNumber),
123 new GenericResultPoint((float) (endRange[1] - endRange[0]) / 2.0f, (float) rowNumber)});
127 * Computes the UPC/EAN checksum on a string of digits, and reports
128 * whether the checksum is correct or not.
130 * @param s string of digits to check
131 * @return true iff string of digits passes the UPC/EAN checksum algorithm
132 * @throws ReaderException if the string does not contain only digits
134 protected boolean checkChecksum(String s) throws ReaderException {
136 int length = s.length();
137 for (int i = length - 2; 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");
145 for (int i = length - 1; i >= 0; i -= 2) {
146 int digit = (int) s.charAt(i) - (int) '0';
147 if (digit < 0 || digit > 9) {
148 throw new ReaderException("Illegal character during checksum");
152 return sum % 10 == 0;
156 * Subclasses override this to decode the portion of a barcode between the start and end guard patterns.
158 * @param row row of black/white values to search
159 * @param startRange start/end offset of start guard pattern
160 * @param resultString {@link StringBuffer} to append decoded chars to
161 * @return horizontal offset of first pixel after the "middle" that was decoded
162 * @throws ReaderException if decoding could not complete successfully
164 protected abstract int decodeMiddle(BitArray row, int[] startRange, StringBuffer resultString)
165 throws ReaderException;
167 protected int[] decodeEnd(BitArray row, int endStart) throws ReaderException {
168 return findGuardPattern(row, endStart, false, START_END_PATTERN);
172 * @param row row of black/white values to search
173 * @param rowOffset position to start search
174 * @param whiteFirst if true, indicates that the pattern specifies white/black/white/...
175 * pixel counts, otherwise, it is interpreted as black/white/black/...
176 * @param pattern pattern of counts of number of black and white pixels that are being
177 * searched for as a pattern
178 * @return start/end horizontal offset of guard pattern, as an array of two ints
179 * @throws ReaderException if pattern is not found
181 protected static int[] findGuardPattern(BitArray row, int rowOffset, boolean whiteFirst, int[] pattern)
182 throws ReaderException {
183 int patternLength = pattern.length;
184 int[] counters = new int[patternLength];
185 int width = row.getSize();
186 boolean isWhite = false;
187 while (rowOffset < width) {
188 isWhite = !row.get(rowOffset);
189 if (whiteFirst == isWhite) {
195 int counterPosition = 0;
196 int patternStart = rowOffset;
197 for (int x = rowOffset; x < width; x++) {
198 boolean pixel = row.get(x);
199 if ((!pixel && isWhite) || (pixel && !isWhite)) {
200 counters[counterPosition]++;
202 if (counterPosition == patternLength - 1) {
203 if (patternMatchVariance(counters, pattern) < MAX_VARIANCE) {
204 return new int[]{patternStart, x};
206 patternStart += counters[0] + counters[1];
207 for (int y = 2; y < patternLength; y++) {
208 counters[y - 2] = counters[y];
210 counters[patternLength - 2] = 0;
211 counters[patternLength - 1] = 0;
216 counters[counterPosition] = 1;
220 throw new ReaderException("Can't find pattern");
224 * Attempts to decode a single UPC/EAN-encoded digit.
226 * @param row row of black/white values to decode
227 * @param counters the counts of runs of observed black/white/black/... values
228 * @param rowOffset horizontal offset to start decoding from
229 * @param patterns the set of patterns to use to decode -- sometimes different encodings
230 * for the digits 0-9 are used, and this indicates the encodings for 0 to 9 that should
232 * @return horizontal offset of first pixel beyond the decoded digit
233 * @throws ReaderException if digit cannot be decoded
235 protected static int decodeDigit(BitArray row,
238 int[][] patterns) throws ReaderException {
239 recordPattern(row, rowOffset, counters);
240 float bestVariance = MAX_VARIANCE; // worst variance we'll accept
242 for (int d = 0; d < patterns.length; d++) {
243 int[] pattern = patterns[d];
244 float variance = patternMatchVariance(counters, pattern);
245 if (variance < bestVariance) {
246 bestVariance = variance;
250 if (bestMatch >= 0) {
253 throw new ReaderException("Could not match any digit in pattern");