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.ChecksumException;
21 import com.google.zxing.DecodeHintType;
22 import com.google.zxing.FormatException;
23 import com.google.zxing.NotFoundException;
24 import com.google.zxing.Result;
25 import com.google.zxing.ResultPoint;
26 import com.google.zxing.ResultPointCallback;
27 import com.google.zxing.common.BitArray;
29 import java.util.Hashtable;
32 * <p>Encapsulates functionality and implementation that is common to UPC and EAN families
33 * of one-dimensional barcodes.</p>
35 * @author dswitkin@google.com (Daniel Switkin)
37 * @author alasdair@google.com (Alasdair Mackintosh)
39 public abstract class UPCEANReader extends OneDReader {
41 // These two values are critical for determining how permissive the decoding will be.
42 // We've arrived at these values through a lot of trial and error. Setting them any higher
43 // lets false positives creep in quickly.
44 private static final int MAX_AVG_VARIANCE = (int) (PATTERN_MATCH_RESULT_SCALE_FACTOR * 0.42f);
45 private static final int MAX_INDIVIDUAL_VARIANCE = (int) (PATTERN_MATCH_RESULT_SCALE_FACTOR * 0.7f);
48 * Start/end guard pattern.
50 static final int[] START_END_PATTERN = {1, 1, 1,};
53 * Pattern marking the middle of a UPC/EAN pattern, separating the two halves.
55 static final int[] MIDDLE_PATTERN = {1, 1, 1, 1, 1};
58 * "Odd", or "L" patterns used to encode UPC/EAN digits.
60 static final int[][] L_PATTERNS = {
74 * As above but also including the "even", or "G" patterns used to encode UPC/EAN digits.
76 static final int[][] L_AND_G_PATTERNS;
79 L_AND_G_PATTERNS = new int[20][];
80 for (int i = 0; i < 10; i++) {
81 L_AND_G_PATTERNS[i] = L_PATTERNS[i];
83 for (int i = 10; i < 20; i++) {
84 int[] widths = L_PATTERNS[i - 10];
85 int[] reversedWidths = new int[widths.length];
86 for (int j = 0; j < widths.length; j++) {
87 reversedWidths[j] = widths[widths.length - j - 1];
89 L_AND_G_PATTERNS[i] = reversedWidths;
93 private final StringBuffer decodeRowStringBuffer;
95 protected UPCEANReader() {
96 decodeRowStringBuffer = new StringBuffer(20);
99 static int[] findStartGuardPattern(BitArray row) throws NotFoundException {
100 boolean foundStart = false;
101 int[] startRange = null;
103 while (!foundStart) {
104 startRange = findGuardPattern(row, nextStart, false, START_END_PATTERN);
105 int start = startRange[0];
106 nextStart = startRange[1];
107 // Make sure there is a quiet zone at least as big as the start pattern before the barcode.
108 // If this check would run off the left edge of the image, do not accept this barcode,
109 // as it is very likely to be a false positive.
110 int quietStart = start - (nextStart - start);
111 if (quietStart >= 0) {
112 foundStart = row.isRange(quietStart, start, false);
118 public Result decodeRow(int rowNumber, BitArray row, Hashtable hints)
119 throws NotFoundException, ChecksumException, FormatException {
120 return decodeRow(rowNumber, row, findStartGuardPattern(row), hints);
124 * <p>Like {@link #decodeRow(int, BitArray, java.util.Hashtable)}, but
125 * allows caller to inform method about where the UPC/EAN start pattern is
126 * found. This allows this to be computed once and reused across many implementations.</p>
128 public Result decodeRow(int rowNumber, BitArray row, int[] startGuardRange, Hashtable hints)
129 throws NotFoundException, ChecksumException, FormatException {
131 ResultPointCallback resultPointCallback = hints == null ? null :
132 (ResultPointCallback) hints.get(DecodeHintType.NEED_RESULT_POINT_CALLBACK);
134 if (resultPointCallback != null) {
135 resultPointCallback.foundPossibleResultPoint(new ResultPoint(
136 (startGuardRange[0] + startGuardRange[1]) / 2.0f, rowNumber
140 StringBuffer result = decodeRowStringBuffer;
142 int endStart = decodeMiddle(row, startGuardRange, result);
144 if (resultPointCallback != null) {
145 resultPointCallback.foundPossibleResultPoint(new ResultPoint(
150 int[] endRange = decodeEnd(row, endStart);
152 if (resultPointCallback != null) {
153 resultPointCallback.foundPossibleResultPoint(new ResultPoint(
154 (endRange[0] + endRange[1]) / 2.0f, rowNumber
159 // Make sure there is a quiet zone at least as big as the end pattern after the barcode. The
160 // spec might want more whitespace, but in practice this is the maximum we can count on.
161 int end = endRange[1];
162 int quietEnd = end + (end - endRange[0]);
163 if (quietEnd >= row.getSize() || !row.isRange(end, quietEnd, false)) {
164 throw NotFoundException.getNotFoundInstance();
167 String resultString = result.toString();
168 if (!checkChecksum(resultString)) {
169 throw ChecksumException.getChecksumInstance();
172 float left = (float) (startGuardRange[1] + startGuardRange[0]) / 2.0f;
173 float right = (float) (endRange[1] + endRange[0]) / 2.0f;
174 return new Result(resultString,
175 null, // no natural byte representation for these barcodes
177 new ResultPoint(left, (float) rowNumber),
178 new ResultPoint(right, (float) rowNumber)},
183 * @return {@link #checkStandardUPCEANChecksum(String)}
185 boolean checkChecksum(String s) throws ChecksumException, FormatException {
186 return checkStandardUPCEANChecksum(s);
190 * Computes the UPC/EAN checksum on a string of digits, and reports
191 * whether the checksum is correct or not.
193 * @param s string of digits to check
194 * @return true iff string of digits passes the UPC/EAN checksum algorithm
195 * @throws FormatException if the string does not contain only digits
196 * @throws ChecksumException if checksum mismatches
198 private static boolean checkStandardUPCEANChecksum(String s) throws ChecksumException, FormatException {
199 int length = s.length();
205 for (int i = length - 2; i >= 0; i -= 2) {
206 int digit = (int) s.charAt(i) - (int) '0';
207 if (digit < 0 || digit > 9) {
208 throw FormatException.getFormatInstance();
213 for (int i = length - 1; i >= 0; i -= 2) {
214 int digit = (int) s.charAt(i) - (int) '0';
215 if (digit < 0 || digit > 9) {
216 throw ChecksumException.getChecksumInstance();
220 return sum % 10 == 0;
223 int[] decodeEnd(BitArray row, int endStart) throws NotFoundException {
224 return findGuardPattern(row, endStart, false, START_END_PATTERN);
228 * @param row row of black/white values to search
229 * @param rowOffset position to start search
230 * @param whiteFirst if true, indicates that the pattern specifies white/black/white/...
231 * pixel counts, otherwise, it is interpreted as black/white/black/...
232 * @param pattern pattern of counts of number of black and white pixels that are being
233 * searched for as a pattern
234 * @return start/end horizontal offset of guard pattern, as an array of two ints
235 * @throws NotFoundException if pattern is not found
237 static int[] findGuardPattern(BitArray row, int rowOffset, boolean whiteFirst, int[] pattern)
238 throws NotFoundException {
239 int patternLength = pattern.length;
240 int[] counters = new int[patternLength];
241 int width = row.getSize();
242 boolean isWhite = false;
243 while (rowOffset < width) {
244 isWhite = !row.get(rowOffset);
245 if (whiteFirst == isWhite) {
251 int counterPosition = 0;
252 int patternStart = rowOffset;
253 for (int x = rowOffset; x < width; x++) {
254 boolean pixel = row.get(x);
255 if (pixel ^ isWhite) {
256 counters[counterPosition]++;
258 if (counterPosition == patternLength - 1) {
259 if (patternMatchVariance(counters, pattern, MAX_INDIVIDUAL_VARIANCE) < MAX_AVG_VARIANCE) {
260 return new int[]{patternStart, x};
262 patternStart += counters[0] + counters[1];
263 for (int y = 2; y < patternLength; y++) {
264 counters[y - 2] = counters[y];
266 counters[patternLength - 2] = 0;
267 counters[patternLength - 1] = 0;
272 counters[counterPosition] = 1;
276 throw NotFoundException.getNotFoundInstance();
280 * Attempts to decode a single UPC/EAN-encoded digit.
282 * @param row row of black/white values to decode
283 * @param counters the counts of runs of observed black/white/black/... values
284 * @param rowOffset horizontal offset to start decoding from
285 * @param patterns the set of patterns to use to decode -- sometimes different encodings
286 * for the digits 0-9 are used, and this indicates the encodings for 0 to 9 that should
288 * @return horizontal offset of first pixel beyond the decoded digit
289 * @throws NotFoundException if digit cannot be decoded
291 static int decodeDigit(BitArray row, int[] counters, int rowOffset, int[][] patterns)
292 throws NotFoundException {
293 recordPattern(row, rowOffset, counters);
294 int bestVariance = MAX_AVG_VARIANCE; // worst variance we'll accept
296 int max = patterns.length;
297 for (int i = 0; i < max; i++) {
298 int[] pattern = patterns[i];
299 int variance = patternMatchVariance(counters, pattern, MAX_INDIVIDUAL_VARIANCE);
300 if (variance < bestVariance) {
301 bestVariance = variance;
305 if (bestMatch >= 0) {
308 throw NotFoundException.getNotFoundInstance();
313 * Get the format of this decoder.
315 * @return The 1D format.
317 abstract BarcodeFormat getBarcodeFormat();
320 * Subclasses override this to decode the portion of a barcode between the start
321 * and end guard patterns.
323 * @param row row of black/white values to search
324 * @param startRange start/end offset of start guard pattern
325 * @param resultString {@link StringBuffer} to append decoded chars to
326 * @return horizontal offset of first pixel after the "middle" that was decoded
327 * @throws NotFoundException if decoding could not complete successfully
329 protected abstract int decodeMiddle(BitArray row, int[] startRange, StringBuffer resultString)
330 throws NotFoundException;