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.FormatException;
22 import com.google.zxing.NotFoundException;
23 import com.google.zxing.Result;
24 import com.google.zxing.ResultPoint;
25 import com.google.zxing.common.BitArray;
27 import java.util.Hashtable;
30 * <p>Decodes Code 39 barcodes. This does not support "Full ASCII Code 39" yet.</p>
34 public final class Code39Reader extends OneDReader {
36 static final String ALPHABET_STRING = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. *$/+%";
37 private static final char[] ALPHABET = ALPHABET_STRING.toCharArray();
40 * These represent the encodings of characters, as patterns of wide and narrow bars.
41 * The 9 least-significant bits of each int correspond to the pattern of wide and narrow,
42 * with 1s representing "wide" and 0s representing narrow.
44 static final int[] CHARACTER_ENCODINGS = {
45 0x034, 0x121, 0x061, 0x160, 0x031, 0x130, 0x070, 0x025, 0x124, 0x064, // 0-9
46 0x109, 0x049, 0x148, 0x019, 0x118, 0x058, 0x00D, 0x10C, 0x04C, 0x01C, // A-J
47 0x103, 0x043, 0x142, 0x013, 0x112, 0x052, 0x007, 0x106, 0x046, 0x016, // K-T
48 0x181, 0x0C1, 0x1C0, 0x091, 0x190, 0x0D0, 0x085, 0x184, 0x0C4, 0x094, // U-*
49 0x0A8, 0x0A2, 0x08A, 0x02A // $-%
52 private static final int ASTERISK_ENCODING = CHARACTER_ENCODINGS[39];
54 private final boolean usingCheckDigit;
55 private final boolean extendedMode;
58 * Creates a reader that assumes all encoded data is data, and does not treat the final
59 * character as a check digit. It will not decoded "extended Code 39" sequences.
61 public Code39Reader() {
62 usingCheckDigit = false;
67 * Creates a reader that can be configured to check the last character as a check digit.
68 * It will not decoded "extended Code 39" sequences.
70 * @param usingCheckDigit if true, treat the last data character as a check digit, not
71 * data, and verify that the checksum passes.
73 public Code39Reader(boolean usingCheckDigit) {
74 this.usingCheckDigit = usingCheckDigit;
75 this.extendedMode = false;
79 * Creates a reader that can be configured to check the last character as a check digit,
80 * or optionally attempt to decode "extended Code 39" sequences that are used to encode
81 * the full ASCII character set.
83 * @param usingCheckDigit if true, treat the last data character as a check digit, not
84 * data, and verify that the checksum passes.
85 * @param extendedMode if true, will attempt to decode extended Code 39 sequences in the
88 public Code39Reader(boolean usingCheckDigit, boolean extendedMode) {
89 this.usingCheckDigit = usingCheckDigit;
90 this.extendedMode = extendedMode;
93 public Result decodeRow(int rowNumber, BitArray row, Hashtable hints)
94 throws NotFoundException, ChecksumException, FormatException {
96 int[] start = findAsteriskPattern(row);
97 int nextStart = start[1];
98 int end = row.getSize();
100 // Read off white space
101 while (nextStart < end && !row.get(nextStart)) {
105 StringBuffer result = new StringBuffer(20);
106 int[] counters = new int[9];
110 recordPattern(row, nextStart, counters);
111 int pattern = toNarrowWidePattern(counters);
113 throw NotFoundException.getNotFoundInstance();
115 decodedChar = patternToChar(pattern);
116 result.append(decodedChar);
117 lastStart = nextStart;
118 for (int i = 0; i < counters.length; i++) {
119 nextStart += counters[i];
121 // Read off white space
122 while (nextStart < end && !row.get(nextStart)) {
125 } while (decodedChar != '*');
126 result.deleteCharAt(result.length() - 1); // remove asterisk
128 // Look for whitespace after pattern:
129 int lastPatternSize = 0;
130 for (int i = 0; i < counters.length; i++) {
131 lastPatternSize += counters[i];
133 int whiteSpaceAfterEnd = nextStart - lastStart - lastPatternSize;
134 // If 50% of last pattern size, following last pattern, is not whitespace, fail
135 // (but if it's whitespace to the very end of the image, that's OK)
136 if (nextStart != end && whiteSpaceAfterEnd / 2 < lastPatternSize) {
137 throw NotFoundException.getNotFoundInstance();
140 if (usingCheckDigit) {
141 int max = result.length() - 1;
143 for (int i = 0; i < max; i++) {
144 total += ALPHABET_STRING.indexOf(result.charAt(i));
146 if (total % 43 != ALPHABET_STRING.indexOf(result.charAt(max))) {
147 throw ChecksumException.getChecksumInstance();
149 result.deleteCharAt(max);
152 String resultString = result.toString();
154 resultString = decodeExtended(resultString);
157 if (resultString.length() == 0) {
158 // Almost surely a false positive
159 throw NotFoundException.getNotFoundInstance();
162 float left = (float) (start[1] + start[0]) / 2.0f;
163 float right = (float) (nextStart + lastStart) / 2.0f;
168 new ResultPoint(left, (float) rowNumber),
169 new ResultPoint(right, (float) rowNumber)},
170 BarcodeFormat.CODE_39);
174 private static int[] findAsteriskPattern(BitArray row) throws NotFoundException {
175 int width = row.getSize();
177 while (rowOffset < width) {
178 if (row.get(rowOffset)) {
184 int counterPosition = 0;
185 int[] counters = new int[9];
186 int patternStart = rowOffset;
187 boolean isWhite = false;
188 int patternLength = counters.length;
190 for (int i = rowOffset; i < width; i++) {
191 boolean pixel = row.get(i);
192 if (pixel ^ isWhite) {
193 counters[counterPosition]++;
195 if (counterPosition == patternLength - 1) {
196 if (toNarrowWidePattern(counters) == ASTERISK_ENCODING) {
197 // Look for whitespace before start pattern, >= 50% of width of start pattern
198 if (row.isRange(Math.max(0, patternStart - (i - patternStart) / 2), patternStart, false)) {
199 return new int[]{patternStart, i};
202 patternStart += counters[0] + counters[1];
203 for (int y = 2; y < patternLength; y++) {
204 counters[y - 2] = counters[y];
206 counters[patternLength - 2] = 0;
207 counters[patternLength - 1] = 0;
212 counters[counterPosition] = 1;
216 throw NotFoundException.getNotFoundInstance();
219 // For efficiency, returns -1 on failure. Not throwing here saved as many as 700 exceptions
220 // per image when using some of our blackbox images.
221 private static int toNarrowWidePattern(int[] counters) {
222 int numCounters = counters.length;
223 int maxNarrowCounter = 0;
226 int minCounter = Integer.MAX_VALUE;
227 for (int i = 0; i < numCounters; i++) {
228 int counter = counters[i];
229 if (counter < minCounter && counter > maxNarrowCounter) {
230 minCounter = counter;
233 maxNarrowCounter = minCounter;
235 int totalWideCountersWidth = 0;
237 for (int i = 0; i < numCounters; i++) {
238 int counter = counters[i];
239 if (counters[i] > maxNarrowCounter) {
240 pattern |= 1 << (numCounters - 1 - i);
242 totalWideCountersWidth += counter;
245 if (wideCounters == 3) {
246 // Found 3 wide counters, but are they close enough in width?
247 // We can perform a cheap, conservative check to see if any individual
248 // counter is more than 1.5 times the average:
249 for (int i = 0; i < numCounters && wideCounters > 0; i++) {
250 int counter = counters[i];
251 if (counters[i] > maxNarrowCounter) {
253 // totalWideCountersWidth = 3 * average, so this checks if counter >= 3/2 * average
254 if ((counter << 1) >= totalWideCountersWidth) {
261 } while (wideCounters > 3);
265 private static char patternToChar(int pattern) throws NotFoundException {
266 for (int i = 0; i < CHARACTER_ENCODINGS.length; i++) {
267 if (CHARACTER_ENCODINGS[i] == pattern) {
271 throw NotFoundException.getNotFoundInstance();
274 private static String decodeExtended(String encoded) throws FormatException {
275 int length = encoded.length();
276 StringBuffer decoded = new StringBuffer(length);
277 for (int i = 0; i < length; i++) {
278 char c = encoded.charAt(i);
279 if (c == '+' || c == '$' || c == '%' || c == '/') {
280 char next = encoded.charAt(i + 1);
281 char decodedChar = '\0';
284 // +A to +Z map to a to z
285 if (next >= 'A' && next <= 'Z') {
286 decodedChar = (char) (next + 32);
288 throw FormatException.getFormatInstance();
292 // $A to $Z map to control codes SH to SB
293 if (next >= 'A' && next <= 'Z') {
294 decodedChar = (char) (next - 64);
296 throw FormatException.getFormatInstance();
300 // %A to %E map to control codes ESC to US
301 if (next >= 'A' && next <= 'E') {
302 decodedChar = (char) (next - 38);
303 } else if (next >= 'F' && next <= 'W') {
304 decodedChar = (char) (next - 11);
306 throw FormatException.getFormatInstance();
310 // /A to /O map to ! to , and /Z maps to :
311 if (next >= 'A' && next <= 'O') {
312 decodedChar = (char) (next - 32);
313 } else if (next == 'Z') {
316 throw FormatException.getFormatInstance();
320 decoded.append(decodedChar);
321 // bump up i again since we read two characters
327 return decoded.toString();