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>
35 public final class Code39Reader extends OneDReader {
37 static final String ALPHABET_STRING = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. *$/+%";
38 private static final char[] ALPHABET = ALPHABET_STRING.toCharArray();
41 * These represent the encodings of characters, as patterns of wide and narrow bars.
42 * The 9 least-significant bits of each int correspond to the pattern of wide and narrow,
43 * with 1s representing "wide" and 0s representing narrow.
45 static final int[] CHARACTER_ENCODINGS = {
46 0x034, 0x121, 0x061, 0x160, 0x031, 0x130, 0x070, 0x025, 0x124, 0x064, // 0-9
47 0x109, 0x049, 0x148, 0x019, 0x118, 0x058, 0x00D, 0x10C, 0x04C, 0x01C, // A-J
48 0x103, 0x043, 0x142, 0x013, 0x112, 0x052, 0x007, 0x106, 0x046, 0x016, // K-T
49 0x181, 0x0C1, 0x1C0, 0x091, 0x190, 0x0D0, 0x085, 0x184, 0x0C4, 0x094, // U-*
50 0x0A8, 0x0A2, 0x08A, 0x02A // $-%
53 private static final int ASTERISK_ENCODING = CHARACTER_ENCODINGS[39];
55 private final boolean usingCheckDigit;
56 private final boolean extendedMode;
59 * Creates a reader that assumes all encoded data is data, and does not treat the final
60 * character as a check digit. It will not decoded "extended Code 39" sequences.
62 public Code39Reader() {
63 usingCheckDigit = false;
68 * Creates a reader that can be configured to check the last character as a check digit.
69 * It will not decoded "extended Code 39" sequences.
71 * @param usingCheckDigit if true, treat the last data character as a check digit, not
72 * data, and verify that the checksum passes.
74 public Code39Reader(boolean usingCheckDigit) {
75 this.usingCheckDigit = usingCheckDigit;
76 this.extendedMode = false;
80 * Creates a reader that can be configured to check the last character as a check digit,
81 * or optionally attempt to decode "extended Code 39" sequences that are used to encode
82 * the full ASCII character set.
84 * @param usingCheckDigit if true, treat the last data character as a check digit, not
85 * data, and verify that the checksum passes.
86 * @param extendedMode if true, will attempt to decode extended Code 39 sequences in the
89 public Code39Reader(boolean usingCheckDigit, boolean extendedMode) {
90 this.usingCheckDigit = usingCheckDigit;
91 this.extendedMode = extendedMode;
94 public Result decodeRow(int rowNumber, BitArray row, Hashtable hints)
95 throws NotFoundException, ChecksumException, FormatException {
97 int[] start = findAsteriskPattern(row);
98 int nextStart = start[1];
99 int end = row.getSize();
101 // Read off white space
102 while (nextStart < end && !row.get(nextStart)) {
106 StringBuffer result = new StringBuffer(20);
107 int[] counters = new int[9];
111 recordPattern(row, nextStart, counters);
112 int pattern = toNarrowWidePattern(counters);
114 throw NotFoundException.getNotFoundInstance();
116 decodedChar = patternToChar(pattern);
117 result.append(decodedChar);
118 lastStart = nextStart;
119 for (int i = 0; i < counters.length; i++) {
120 nextStart += counters[i];
122 // Read off white space
123 while (nextStart < end && !row.get(nextStart)) {
126 } while (decodedChar != '*');
127 result.deleteCharAt(result.length() - 1); // remove asterisk
129 // Look for whitespace after pattern:
130 int lastPatternSize = 0;
131 for (int i = 0; i < counters.length; i++) {
132 lastPatternSize += counters[i];
134 int whiteSpaceAfterEnd = nextStart - lastStart - lastPatternSize;
135 // If 50% of last pattern size, following last pattern, is not whitespace, fail
136 // (but if it's whitespace to the very end of the image, that's OK)
137 if (nextStart != end && whiteSpaceAfterEnd / 2 < lastPatternSize) {
138 throw NotFoundException.getNotFoundInstance();
141 if (usingCheckDigit) {
142 int max = result.length() - 1;
144 for (int i = 0; i < max; i++) {
145 total += ALPHABET_STRING.indexOf(result.charAt(i));
147 if (result.charAt(max) != ALPHABET[total % 43]) {
148 throw ChecksumException.getChecksumInstance();
150 result.deleteCharAt(max);
153 if (result.length() == 0) {
154 // Almost surely a false positive
155 throw NotFoundException.getNotFoundInstance();
160 resultString = decodeExtended(result);
162 resultString = result.toString();
165 float left = (float) (start[1] + start[0]) / 2.0f;
166 float right = (float) (nextStart + lastStart) / 2.0f;
171 new ResultPoint(left, (float) rowNumber),
172 new ResultPoint(right, (float) rowNumber)},
173 BarcodeFormat.CODE_39);
177 private static int[] findAsteriskPattern(BitArray row) throws NotFoundException {
178 int width = row.getSize();
180 while (rowOffset < width) {
181 if (row.get(rowOffset)) {
187 int counterPosition = 0;
188 int[] counters = new int[9];
189 int patternStart = rowOffset;
190 boolean isWhite = false;
191 int patternLength = counters.length;
193 for (int i = rowOffset; i < width; i++) {
194 boolean pixel = row.get(i);
195 if (pixel ^ isWhite) {
196 counters[counterPosition]++;
198 if (counterPosition == patternLength - 1) {
199 if (toNarrowWidePattern(counters) == ASTERISK_ENCODING) {
200 // Look for whitespace before start pattern, >= 50% of width of start pattern
201 if (row.isRange(Math.max(0, patternStart - (i - patternStart) / 2), patternStart, false)) {
202 return new int[]{patternStart, i};
205 patternStart += counters[0] + counters[1];
206 for (int y = 2; y < patternLength; y++) {
207 counters[y - 2] = counters[y];
209 counters[patternLength - 2] = 0;
210 counters[patternLength - 1] = 0;
215 counters[counterPosition] = 1;
219 throw NotFoundException.getNotFoundInstance();
222 // For efficiency, returns -1 on failure. Not throwing here saved as many as 700 exceptions
223 // per image when using some of our blackbox images.
224 private static int toNarrowWidePattern(int[] counters) {
225 int numCounters = counters.length;
226 int maxNarrowCounter = 0;
229 int minCounter = Integer.MAX_VALUE;
230 for (int i = 0; i < numCounters; i++) {
231 int counter = counters[i];
232 if (counter < minCounter && counter > maxNarrowCounter) {
233 minCounter = counter;
236 maxNarrowCounter = minCounter;
238 int totalWideCountersWidth = 0;
240 for (int i = 0; i < numCounters; i++) {
241 int counter = counters[i];
242 if (counters[i] > maxNarrowCounter) {
243 pattern |= 1 << (numCounters - 1 - i);
245 totalWideCountersWidth += counter;
248 if (wideCounters == 3) {
249 // Found 3 wide counters, but are they close enough in width?
250 // We can perform a cheap, conservative check to see if any individual
251 // counter is more than 1.5 times the average:
252 for (int i = 0; i < numCounters && wideCounters > 0; i++) {
253 int counter = counters[i];
254 if (counters[i] > maxNarrowCounter) {
256 // totalWideCountersWidth = 3 * average, so this checks if counter >= 3/2 * average
257 if ((counter << 1) >= totalWideCountersWidth) {
264 } while (wideCounters > 3);
268 private static char patternToChar(int pattern) throws NotFoundException {
269 for (int i = 0; i < CHARACTER_ENCODINGS.length; i++) {
270 if (CHARACTER_ENCODINGS[i] == pattern) {
274 throw NotFoundException.getNotFoundInstance();
277 private static String decodeExtended(StringBuffer encoded) throws FormatException {
278 int length = encoded.length();
279 StringBuffer decoded = new StringBuffer(length);
280 for (int i = 0; i < length; i++) {
281 char c = encoded.charAt(i);
282 if (c == '+' || c == '$' || c == '%' || c == '/') {
283 char next = encoded.charAt(i + 1);
284 char decodedChar = '\0';
287 // +A to +Z map to a to z
288 if (next >= 'A' && next <= 'Z') {
289 decodedChar = (char) (next + 32);
291 throw FormatException.getFormatInstance();
295 // $A to $Z map to control codes SH to SB
296 if (next >= 'A' && next <= 'Z') {
297 decodedChar = (char) (next - 64);
299 throw FormatException.getFormatInstance();
303 // %A to %E map to control codes ESC to US
304 if (next >= 'A' && next <= 'E') {
305 decodedChar = (char) (next - 38);
306 } else if (next >= 'F' && next <= 'W') {
307 decodedChar = (char) (next - 11);
309 throw FormatException.getFormatInstance();
313 // /A to /O map to ! to , and /Z maps to :
314 if (next >= 'A' && next <= 'O') {
315 decodedChar = (char) (next - 32);
316 } else if (next == 'Z') {
319 throw FormatException.getFormatInstance();
323 decoded.append(decodedChar);
324 // bump up i again since we read two characters
330 return decoded.toString();