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.ReaderException;
25 import com.google.zxing.Result;
26 import com.google.zxing.ResultMetadataType;
27 import com.google.zxing.ResultPoint;
28 import com.google.zxing.ResultPointCallback;
29 import com.google.zxing.common.BitArray;
31 import java.util.Hashtable;
34 * <p>Encapsulates functionality and implementation that is common to UPC and EAN families
35 * of one-dimensional barcodes.</p>
37 * @author dswitkin@google.com (Daniel Switkin)
39 * @author alasdair@google.com (Alasdair Mackintosh)
41 public abstract class UPCEANReader extends OneDReader {
43 // These two values are critical for determining how permissive the decoding will be.
44 // We've arrived at these values through a lot of trial and error. Setting them any higher
45 // lets false positives creep in quickly.
46 private static final int MAX_AVG_VARIANCE = (int) (PATTERN_MATCH_RESULT_SCALE_FACTOR * 0.42f);
47 private static final int MAX_INDIVIDUAL_VARIANCE = (int) (PATTERN_MATCH_RESULT_SCALE_FACTOR * 0.7f);
50 * Start/end guard pattern.
52 static final int[] START_END_PATTERN = {1, 1, 1,};
55 * Pattern marking the middle of a UPC/EAN pattern, separating the two halves.
57 static final int[] MIDDLE_PATTERN = {1, 1, 1, 1, 1};
60 * "Odd", or "L" patterns used to encode UPC/EAN digits.
62 static final int[][] L_PATTERNS = {
76 * As above but also including the "even", or "G" patterns used to encode UPC/EAN digits.
78 static final int[][] L_AND_G_PATTERNS;
81 L_AND_G_PATTERNS = new int[20][];
82 for (int i = 0; i < 10; i++) {
83 L_AND_G_PATTERNS[i] = L_PATTERNS[i];
85 for (int i = 10; i < 20; i++) {
86 int[] widths = L_PATTERNS[i - 10];
87 int[] reversedWidths = new int[widths.length];
88 for (int j = 0; j < widths.length; j++) {
89 reversedWidths[j] = widths[widths.length - j - 1];
91 L_AND_G_PATTERNS[i] = reversedWidths;
95 private final StringBuffer decodeRowStringBuffer;
96 private final UPCEANExtensionSupport extensionReader;
97 private final EANManufacturerOrgSupport eanManSupport;
99 protected UPCEANReader() {
100 decodeRowStringBuffer = new StringBuffer(20);
101 extensionReader = new UPCEANExtensionSupport();
102 eanManSupport = new EANManufacturerOrgSupport();
105 static int[] findStartGuardPattern(BitArray row) throws NotFoundException {
106 boolean foundStart = false;
107 int[] startRange = null;
109 while (!foundStart) {
110 startRange = findGuardPattern(row, nextStart, false, START_END_PATTERN);
111 int start = startRange[0];
112 nextStart = startRange[1];
113 // Make sure there is a quiet zone at least as big as the start pattern before the barcode.
114 // If this check would run off the left edge of the image, do not accept this barcode,
115 // as it is very likely to be a false positive.
116 int quietStart = start - (nextStart - start);
117 if (quietStart >= 0) {
118 foundStart = row.isRange(quietStart, start, false);
124 public Result decodeRow(int rowNumber, BitArray row, Hashtable hints)
125 throws NotFoundException, ChecksumException, FormatException {
126 return decodeRow(rowNumber, row, findStartGuardPattern(row), hints);
130 * <p>Like {@link #decodeRow(int, BitArray, java.util.Hashtable)}, but
131 * allows caller to inform method about where the UPC/EAN start pattern is
132 * found. This allows this to be computed once and reused across many implementations.</p>
134 public Result decodeRow(int rowNumber, BitArray row, int[] startGuardRange, Hashtable hints)
135 throws NotFoundException, ChecksumException, FormatException {
137 ResultPointCallback resultPointCallback = hints == null ? null :
138 (ResultPointCallback) hints.get(DecodeHintType.NEED_RESULT_POINT_CALLBACK);
140 if (resultPointCallback != null) {
141 resultPointCallback.foundPossibleResultPoint(new ResultPoint(
142 (startGuardRange[0] + startGuardRange[1]) / 2.0f, rowNumber
146 StringBuffer result = decodeRowStringBuffer;
148 int endStart = decodeMiddle(row, startGuardRange, result);
150 if (resultPointCallback != null) {
151 resultPointCallback.foundPossibleResultPoint(new ResultPoint(
156 int[] endRange = decodeEnd(row, endStart);
158 if (resultPointCallback != null) {
159 resultPointCallback.foundPossibleResultPoint(new ResultPoint(
160 (endRange[0] + endRange[1]) / 2.0f, rowNumber
165 // Make sure there is a quiet zone at least as big as the end pattern after the barcode. The
166 // spec might want more whitespace, but in practice this is the maximum we can count on.
167 int end = endRange[1];
168 int quietEnd = end + (end - endRange[0]);
169 if (quietEnd >= row.getSize() || !row.isRange(end, quietEnd, false)) {
170 throw NotFoundException.getNotFoundInstance();
173 String resultString = result.toString();
174 if (!checkChecksum(resultString)) {
175 throw ChecksumException.getChecksumInstance();
178 float left = (float) (startGuardRange[1] + startGuardRange[0]) / 2.0f;
179 float right = (float) (endRange[1] + endRange[0]) / 2.0f;
180 BarcodeFormat format = getBarcodeFormat();
181 Result decodeResult = new Result(resultString,
182 null, // no natural byte representation for these barcodes
184 new ResultPoint(left, (float) rowNumber),
185 new ResultPoint(right, (float) rowNumber)},
189 Result extensionResult = extensionReader.decodeRow(rowNumber, row, endRange[1]);
190 decodeResult.putAllMetadata(extensionResult.getResultMetadata());
191 decodeResult.addResultPoints(extensionResult.getResultPoints());
192 } catch (ReaderException re) {
196 if (BarcodeFormat.EAN_13.equals(format) || BarcodeFormat.UPC_A.equals(format)) {
197 String countryID = eanManSupport.lookupCountryIdentifier(resultString);
198 if (countryID != null) {
199 decodeResult.putMetadata(ResultMetadataType.POSSIBLE_COUNTRY, countryID);
207 * @return {@link #checkStandardUPCEANChecksum(String)}
209 boolean checkChecksum(String s) throws ChecksumException, FormatException {
210 return checkStandardUPCEANChecksum(s);
214 * Computes the UPC/EAN checksum on a string of digits, and reports
215 * whether the checksum is correct or not.
217 * @param s string of digits to check
218 * @return true iff string of digits passes the UPC/EAN checksum algorithm
219 * @throws FormatException if the string does not contain only digits
221 private static boolean checkStandardUPCEANChecksum(String s) throws FormatException {
222 int length = s.length();
228 for (int i = length - 2; i >= 0; i -= 2) {
229 int digit = (int) s.charAt(i) - (int) '0';
230 if (digit < 0 || digit > 9) {
231 throw FormatException.getFormatInstance();
236 for (int i = length - 1; i >= 0; i -= 2) {
237 int digit = (int) s.charAt(i) - (int) '0';
238 if (digit < 0 || digit > 9) {
239 throw FormatException.getFormatInstance();
243 return sum % 10 == 0;
246 int[] decodeEnd(BitArray row, int endStart) throws NotFoundException {
247 return findGuardPattern(row, endStart, false, START_END_PATTERN);
251 * @param row row of black/white values to search
252 * @param rowOffset position to start search
253 * @param whiteFirst if true, indicates that the pattern specifies white/black/white/...
254 * pixel counts, otherwise, it is interpreted as black/white/black/...
255 * @param pattern pattern of counts of number of black and white pixels that are being
256 * searched for as a pattern
257 * @return start/end horizontal offset of guard pattern, as an array of two ints
258 * @throws NotFoundException if pattern is not found
260 static int[] findGuardPattern(BitArray row, int rowOffset, boolean whiteFirst, int[] pattern)
261 throws NotFoundException {
262 int patternLength = pattern.length;
263 int[] counters = new int[patternLength];
264 int width = row.getSize();
265 boolean isWhite = false;
266 while (rowOffset < width) {
267 isWhite = !row.get(rowOffset);
268 if (whiteFirst == isWhite) {
274 int counterPosition = 0;
275 int patternStart = rowOffset;
276 for (int x = rowOffset; x < width; x++) {
277 boolean pixel = row.get(x);
278 if (pixel ^ isWhite) {
279 counters[counterPosition]++;
281 if (counterPosition == patternLength - 1) {
282 if (patternMatchVariance(counters, pattern, MAX_INDIVIDUAL_VARIANCE) < MAX_AVG_VARIANCE) {
283 return new int[]{patternStart, x};
285 patternStart += counters[0] + counters[1];
286 for (int y = 2; y < patternLength; y++) {
287 counters[y - 2] = counters[y];
289 counters[patternLength - 2] = 0;
290 counters[patternLength - 1] = 0;
295 counters[counterPosition] = 1;
299 throw NotFoundException.getNotFoundInstance();
303 * Attempts to decode a single UPC/EAN-encoded digit.
305 * @param row row of black/white values to decode
306 * @param counters the counts of runs of observed black/white/black/... values
307 * @param rowOffset horizontal offset to start decoding from
308 * @param patterns the set of patterns to use to decode -- sometimes different encodings
309 * for the digits 0-9 are used, and this indicates the encodings for 0 to 9 that should
311 * @return horizontal offset of first pixel beyond the decoded digit
312 * @throws NotFoundException if digit cannot be decoded
314 static int decodeDigit(BitArray row, int[] counters, int rowOffset, int[][] patterns)
315 throws NotFoundException {
316 recordPattern(row, rowOffset, counters);
317 int bestVariance = MAX_AVG_VARIANCE; // worst variance we'll accept
319 int max = patterns.length;
320 for (int i = 0; i < max; i++) {
321 int[] pattern = patterns[i];
322 int variance = patternMatchVariance(counters, pattern, MAX_INDIVIDUAL_VARIANCE);
323 if (variance < bestVariance) {
324 bestVariance = variance;
328 if (bestMatch >= 0) {
331 throw NotFoundException.getNotFoundInstance();
336 * Get the format of this decoder.
338 * @return The 1D format.
340 abstract BarcodeFormat getBarcodeFormat();
343 * Subclasses override this to decode the portion of a barcode between the start
344 * and end guard patterns.
346 * @param row row of black/white values to search
347 * @param startRange start/end offset of start guard pattern
348 * @param resultString {@link StringBuffer} to append decoded chars to
349 * @return horizontal offset of first pixel after the "middle" that was decoded
350 * @throws NotFoundException if decoding could not complete successfully
352 protected abstract int decodeMiddle(BitArray row, int[] startRange, StringBuffer resultString)
353 throws NotFoundException;