2 * Copyright 2008 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.oned;
19 import com.google.zxing.BarcodeFormat;
20 import com.google.zxing.DecodeHintType;
21 import com.google.zxing.ReaderException;
22 import com.google.zxing.Result;
23 import com.google.zxing.ResultPoint;
24 import com.google.zxing.ResultPointCallback;
25 import com.google.zxing.common.BitArray;
27 import java.util.Hashtable;
30 * <p>Encapsulates functionality and implementation that is common to UPC and EAN families
31 * of one-dimensional barcodes.</p>
33 * @author dswitkin@google.com (Daniel Switkin)
35 * @author alasdair@google.com (Alasdair Mackintosh)
37 public abstract class AbstractUPCEANReader extends AbstractOneDReader implements UPCEANReader {
39 private static final int MAX_AVG_VARIANCE = (int) (PATTERN_MATCH_RESULT_SCALE_FACTOR * 0.42f);
40 private static final int MAX_INDIVIDUAL_VARIANCE = (int) (PATTERN_MATCH_RESULT_SCALE_FACTOR * 0.7f);
43 * Start/end guard pattern.
45 static final int[] START_END_PATTERN = {1, 1, 1,};
48 * Pattern marking the middle of a UPC/EAN pattern, separating the two halves.
50 static final int[] MIDDLE_PATTERN = {1, 1, 1, 1, 1};
53 * "Odd", or "L" patterns used to encode UPC/EAN digits.
55 static final int[][] L_PATTERNS = {
69 * As above but also including the "even", or "G" patterns used to encode UPC/EAN digits.
71 static final int[][] L_AND_G_PATTERNS;
74 L_AND_G_PATTERNS = new int[20][];
75 for (int i = 0; i < 10; i++) {
76 L_AND_G_PATTERNS[i] = L_PATTERNS[i];
78 for (int i = 10; i < 20; i++) {
79 int[] widths = L_PATTERNS[i - 10];
80 int[] reversedWidths = new int[widths.length];
81 for (int j = 0; j < widths.length; j++) {
82 reversedWidths[j] = widths[widths.length - j - 1];
84 L_AND_G_PATTERNS[i] = reversedWidths;
88 private final StringBuffer decodeRowStringBuffer;
90 protected AbstractUPCEANReader() {
91 decodeRowStringBuffer = new StringBuffer(20);
94 static int[] findStartGuardPattern(BitArray row) throws ReaderException {
95 boolean foundStart = false;
96 int[] startRange = null;
99 startRange = findGuardPattern(row, nextStart, false, START_END_PATTERN);
100 int start = startRange[0];
101 nextStart = startRange[1];
102 // Make sure there is a quiet zone at least as big as the start pattern before the barcode.
103 // If this check would run off the left edge of the image, do not accept this barcode,
104 // as it is very likely to be a false positive.
105 int quietStart = start - (nextStart - start);
106 if (quietStart >= 0) {
107 foundStart = row.isRange(quietStart, start, false);
113 public final Result decodeRow(int rowNumber, BitArray row, Hashtable hints)
114 throws ReaderException {
115 return decodeRow(rowNumber, row, findStartGuardPattern(row), hints);
118 public final Result decodeRow(int rowNumber, BitArray row, int[] startGuardRange, Hashtable hints)
119 throws ReaderException {
121 ResultPointCallback resultPointCallback = hints == null ? null :
122 (ResultPointCallback) hints.get(DecodeHintType.NEED_RESULT_POINT_CALLBACK);
124 if (resultPointCallback != null) {
125 resultPointCallback.foundPossibleResultPoint(new ResultPoint(
126 (startGuardRange[0] + startGuardRange[1]) / 2.0f, rowNumber
130 StringBuffer result = decodeRowStringBuffer;
132 int endStart = decodeMiddle(row, startGuardRange, result);
134 if (resultPointCallback != null) {
135 resultPointCallback.foundPossibleResultPoint(new ResultPoint(
140 int[] endRange = decodeEnd(row, endStart);
142 if (resultPointCallback != null) {
143 resultPointCallback.foundPossibleResultPoint(new ResultPoint(
144 (endRange[0] + endRange[1]) / 2.0f, rowNumber
149 // Make sure there is a quiet zone at least as big as the end pattern after the barcode. The
150 // spec might want more whitespace, but in practice this is the maximum we can count on.
151 int end = endRange[1];
152 int quietEnd = end + (end - endRange[0]);
153 if (quietEnd >= row.getSize() || !row.isRange(end, quietEnd, false)) {
154 throw ReaderException.getInstance();
157 String resultString = result.toString();
158 if (!checkChecksum(resultString)) {
159 throw ReaderException.getInstance();
162 float left = (float) (startGuardRange[1] + startGuardRange[0]) / 2.0f;
163 float right = (float) (endRange[1] + endRange[0]) / 2.0f;
164 return new Result(resultString,
165 null, // no natural byte representation for these barcodes
167 new ResultPoint(left, (float) rowNumber),
168 new ResultPoint(right, (float) rowNumber)},
172 abstract BarcodeFormat getBarcodeFormat();
175 * @return {@link #checkStandardUPCEANChecksum(String)}
177 boolean checkChecksum(String s) throws ReaderException {
178 return checkStandardUPCEANChecksum(s);
182 * Computes the UPC/EAN checksum on a string of digits, and reports
183 * whether the checksum is correct or not.
185 * @param s string of digits to check
186 * @return true iff string of digits passes the UPC/EAN checksum algorithm
187 * @throws ReaderException if the string does not contain only digits
189 private static boolean checkStandardUPCEANChecksum(String s) throws ReaderException {
190 int length = s.length();
196 for (int i = length - 2; i >= 0; i -= 2) {
197 int digit = (int) s.charAt(i) - (int) '0';
198 if (digit < 0 || digit > 9) {
199 throw ReaderException.getInstance();
204 for (int i = length - 1; i >= 0; i -= 2) {
205 int digit = (int) s.charAt(i) - (int) '0';
206 if (digit < 0 || digit > 9) {
207 throw ReaderException.getInstance();
211 return sum % 10 == 0;
215 * Subclasses override this to decode the portion of a barcode between the start
216 * and end guard patterns.
218 * @param row row of black/white values to search
219 * @param startRange start/end offset of start guard pattern
220 * @param resultString {@link StringBuffer} to append decoded chars to
221 * @return horizontal offset of first pixel after the "middle" that was decoded
222 * @throws ReaderException if decoding could not complete successfully
224 protected abstract int decodeMiddle(BitArray row, int[] startRange, StringBuffer resultString)
225 throws ReaderException;
227 int[] decodeEnd(BitArray row, int endStart) throws ReaderException {
228 return findGuardPattern(row, endStart, false, START_END_PATTERN);
232 * @param row row of black/white values to search
233 * @param rowOffset position to start search
234 * @param whiteFirst if true, indicates that the pattern specifies white/black/white/...
235 * pixel counts, otherwise, it is interpreted as black/white/black/...
236 * @param pattern pattern of counts of number of black and white pixels that are being
237 * searched for as a pattern
238 * @return start/end horizontal offset of guard pattern, as an array of two ints
239 * @throws ReaderException if pattern is not found
241 static int[] findGuardPattern(BitArray row, int rowOffset, boolean whiteFirst, int[] pattern)
242 throws ReaderException {
243 int patternLength = pattern.length;
244 int[] counters = new int[patternLength];
245 int width = row.getSize();
246 boolean isWhite = false;
247 while (rowOffset < width) {
248 isWhite = !row.get(rowOffset);
249 if (whiteFirst == isWhite) {
255 int counterPosition = 0;
256 int patternStart = rowOffset;
257 for (int x = rowOffset; x < width; x++) {
258 boolean pixel = row.get(x);
259 if (pixel ^ isWhite) {
260 counters[counterPosition]++;
262 if (counterPosition == patternLength - 1) {
263 if (patternMatchVariance(counters, pattern, MAX_INDIVIDUAL_VARIANCE) < MAX_AVG_VARIANCE) {
264 return new int[]{patternStart, x};
266 patternStart += counters[0] + counters[1];
267 for (int y = 2; y < patternLength; y++) {
268 counters[y - 2] = counters[y];
270 counters[patternLength - 2] = 0;
271 counters[patternLength - 1] = 0;
276 counters[counterPosition] = 1;
277 isWhite ^= true; // isWhite = !isWhite;
280 throw ReaderException.getInstance();
284 * Attempts to decode a single UPC/EAN-encoded digit.
286 * @param row row of black/white values to decode
287 * @param counters the counts of runs of observed black/white/black/... values
288 * @param rowOffset horizontal offset to start decoding from
289 * @param patterns the set of patterns to use to decode -- sometimes different encodings
290 * for the digits 0-9 are used, and this indicates the encodings for 0 to 9 that should
292 * @return horizontal offset of first pixel beyond the decoded digit
293 * @throws ReaderException if digit cannot be decoded
295 static int decodeDigit(BitArray row, int[] counters, int rowOffset, int[][] patterns)
296 throws ReaderException {
297 recordPattern(row, rowOffset, counters);
298 int bestVariance = MAX_AVG_VARIANCE; // worst variance we'll accept
300 int max = patterns.length;
301 for (int i = 0; i < max; i++) {
302 int[] pattern = patterns[i];
303 int variance = patternMatchVariance(counters, pattern, MAX_INDIVIDUAL_VARIANCE);
304 if (variance < bestVariance) {
305 bestVariance = variance;
309 if (bestMatch >= 0) {
312 throw ReaderException.getInstance();