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 // These two values are critical for determining how permissive the decoding will be.
40 // We've arrived at these values through a lot of trial and error. Setting them any higher
41 // lets false positives creep in quickly.
42 private static final int MAX_AVG_VARIANCE = (int) (PATTERN_MATCH_RESULT_SCALE_FACTOR * 0.42f);
43 private static final int MAX_INDIVIDUAL_VARIANCE = (int) (PATTERN_MATCH_RESULT_SCALE_FACTOR * 0.7f);
46 * Start/end guard pattern.
48 static final int[] START_END_PATTERN = {1, 1, 1,};
51 * Pattern marking the middle of a UPC/EAN pattern, separating the two halves.
53 static final int[] MIDDLE_PATTERN = {1, 1, 1, 1, 1};
56 * "Odd", or "L" patterns used to encode UPC/EAN digits.
58 static final int[][] L_PATTERNS = {
72 * As above but also including the "even", or "G" patterns used to encode UPC/EAN digits.
74 static final int[][] L_AND_G_PATTERNS;
77 L_AND_G_PATTERNS = new int[20][];
78 for (int i = 0; i < 10; i++) {
79 L_AND_G_PATTERNS[i] = L_PATTERNS[i];
81 for (int i = 10; i < 20; i++) {
82 int[] widths = L_PATTERNS[i - 10];
83 int[] reversedWidths = new int[widths.length];
84 for (int j = 0; j < widths.length; j++) {
85 reversedWidths[j] = widths[widths.length - j - 1];
87 L_AND_G_PATTERNS[i] = reversedWidths;
91 private final StringBuffer decodeRowStringBuffer;
93 protected AbstractUPCEANReader() {
94 decodeRowStringBuffer = new StringBuffer(20);
97 static int[] findStartGuardPattern(BitArray row) throws ReaderException {
98 boolean foundStart = false;
99 int[] startRange = null;
101 while (!foundStart) {
102 startRange = findGuardPattern(row, nextStart, false, START_END_PATTERN);
103 int start = startRange[0];
104 nextStart = startRange[1];
105 // Make sure there is a quiet zone at least as big as the start pattern before the barcode.
106 // If this check would run off the left edge of the image, do not accept this barcode,
107 // as it is very likely to be a false positive.
108 int quietStart = start - (nextStart - start);
109 if (quietStart >= 0) {
110 foundStart = row.isRange(quietStart, start, false);
116 public final Result decodeRow(int rowNumber, BitArray row, Hashtable hints)
117 throws ReaderException {
118 return decodeRow(rowNumber, row, findStartGuardPattern(row), hints);
121 public final Result decodeRow(int rowNumber, BitArray row, int[] startGuardRange, Hashtable hints)
122 throws ReaderException {
124 ResultPointCallback resultPointCallback = hints == null ? null :
125 (ResultPointCallback) hints.get(DecodeHintType.NEED_RESULT_POINT_CALLBACK);
127 if (resultPointCallback != null) {
128 resultPointCallback.foundPossibleResultPoint(new ResultPoint(
129 (startGuardRange[0] + startGuardRange[1]) / 2.0f, rowNumber
133 StringBuffer result = decodeRowStringBuffer;
135 int endStart = decodeMiddle(row, startGuardRange, result);
137 if (resultPointCallback != null) {
138 resultPointCallback.foundPossibleResultPoint(new ResultPoint(
143 int[] endRange = decodeEnd(row, endStart);
145 if (resultPointCallback != null) {
146 resultPointCallback.foundPossibleResultPoint(new ResultPoint(
147 (endRange[0] + endRange[1]) / 2.0f, rowNumber
152 // Make sure there is a quiet zone at least as big as the end pattern after the barcode. The
153 // spec might want more whitespace, but in practice this is the maximum we can count on.
154 int end = endRange[1];
155 int quietEnd = end + (end - endRange[0]);
156 if (quietEnd >= row.getSize() || !row.isRange(end, quietEnd, false)) {
157 throw ReaderException.getInstance();
160 String resultString = result.toString();
161 if (!checkChecksum(resultString)) {
162 throw ReaderException.getInstance();
165 float left = (float) (startGuardRange[1] + startGuardRange[0]) / 2.0f;
166 float right = (float) (endRange[1] + endRange[0]) / 2.0f;
167 return new Result(resultString,
168 null, // no natural byte representation for these barcodes
170 new ResultPoint(left, (float) rowNumber),
171 new ResultPoint(right, (float) rowNumber)},
175 abstract BarcodeFormat getBarcodeFormat();
178 * @return {@link #checkStandardUPCEANChecksum(String)}
180 boolean checkChecksum(String s) throws ReaderException {
181 return checkStandardUPCEANChecksum(s);
185 * Computes the UPC/EAN checksum on a string of digits, and reports
186 * whether the checksum is correct or not.
188 * @param s string of digits to check
189 * @return true iff string of digits passes the UPC/EAN checksum algorithm
190 * @throws ReaderException if the string does not contain only digits
192 private static boolean checkStandardUPCEANChecksum(String s) throws ReaderException {
193 int length = s.length();
199 for (int i = length - 2; i >= 0; i -= 2) {
200 int digit = (int) s.charAt(i) - (int) '0';
201 if (digit < 0 || digit > 9) {
202 throw ReaderException.getInstance();
207 for (int i = length - 1; i >= 0; i -= 2) {
208 int digit = (int) s.charAt(i) - (int) '0';
209 if (digit < 0 || digit > 9) {
210 throw ReaderException.getInstance();
214 return sum % 10 == 0;
218 * Subclasses override this to decode the portion of a barcode between the start
219 * and end guard patterns.
221 * @param row row of black/white values to search
222 * @param startRange start/end offset of start guard pattern
223 * @param resultString {@link StringBuffer} to append decoded chars to
224 * @return horizontal offset of first pixel after the "middle" that was decoded
225 * @throws ReaderException if decoding could not complete successfully
227 protected abstract int decodeMiddle(BitArray row, int[] startRange, StringBuffer resultString)
228 throws ReaderException;
230 int[] decodeEnd(BitArray row, int endStart) throws ReaderException {
231 return findGuardPattern(row, endStart, false, START_END_PATTERN);
235 * @param row row of black/white values to search
236 * @param rowOffset position to start search
237 * @param whiteFirst if true, indicates that the pattern specifies white/black/white/...
238 * pixel counts, otherwise, it is interpreted as black/white/black/...
239 * @param pattern pattern of counts of number of black and white pixels that are being
240 * searched for as a pattern
241 * @return start/end horizontal offset of guard pattern, as an array of two ints
242 * @throws ReaderException if pattern is not found
244 static int[] findGuardPattern(BitArray row, int rowOffset, boolean whiteFirst, int[] pattern)
245 throws ReaderException {
246 int patternLength = pattern.length;
247 int[] counters = new int[patternLength];
248 int width = row.getSize();
249 boolean isWhite = false;
250 while (rowOffset < width) {
251 isWhite = !row.get(rowOffset);
252 if (whiteFirst == isWhite) {
258 int counterPosition = 0;
259 int patternStart = rowOffset;
260 for (int x = rowOffset; x < width; x++) {
261 boolean pixel = row.get(x);
262 if (pixel ^ isWhite) {
263 counters[counterPosition]++;
265 if (counterPosition == patternLength - 1) {
266 if (patternMatchVariance(counters, pattern, MAX_INDIVIDUAL_VARIANCE) < MAX_AVG_VARIANCE) {
267 return new int[]{patternStart, x};
269 patternStart += counters[0] + counters[1];
270 for (int y = 2; y < patternLength; y++) {
271 counters[y - 2] = counters[y];
273 counters[patternLength - 2] = 0;
274 counters[patternLength - 1] = 0;
279 counters[counterPosition] = 1;
283 throw ReaderException.getInstance();
287 * Attempts to decode a single UPC/EAN-encoded digit.
289 * @param row row of black/white values to decode
290 * @param counters the counts of runs of observed black/white/black/... values
291 * @param rowOffset horizontal offset to start decoding from
292 * @param patterns the set of patterns to use to decode -- sometimes different encodings
293 * for the digits 0-9 are used, and this indicates the encodings for 0 to 9 that should
295 * @return horizontal offset of first pixel beyond the decoded digit
296 * @throws ReaderException if digit cannot be decoded
298 static int decodeDigit(BitArray row, int[] counters, int rowOffset, int[][] patterns)
299 throws ReaderException {
300 recordPattern(row, rowOffset, counters);
301 int bestVariance = MAX_AVG_VARIANCE; // worst variance we'll accept
303 int max = patterns.length;
304 for (int i = 0; i < max; i++) {
305 int[] pattern = patterns[i];
306 int variance = patternMatchVariance(counters, pattern, MAX_INDIVIDUAL_VARIANCE);
307 if (variance < bestVariance) {
308 bestVariance = variance;
312 if (bestMatch >= 0) {
315 throw ReaderException.getInstance();