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.ReaderException;
21 import com.google.zxing.Result;
22 import com.google.zxing.ResultPoint;
23 import com.google.zxing.common.BitArray;
25 import java.util.Hashtable;
28 * <p>Decodes Code 39 barcodes. This does not support "Full ASCII Code 39" yet.</p>
32 public final class Code39Reader extends AbstractOneDReader {
34 private static final String ALPHABET_STRING = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. *$/+%";
35 private static final char[] ALPHABET = ALPHABET_STRING.toCharArray();
38 * These represent the encodings of characters, as patterns of wide and narrow bars.
39 * The 9 least-significant bits of each int correspond to the pattern of wide and narrow,
40 * with 1s representing "wide" and 0s representing narrow.
42 private static final int[] CHARACTER_ENCODINGS = {
43 0x034, 0x121, 0x061, 0x160, 0x031, 0x130, 0x070, 0x025, 0x124, 0x064, // 0-9
44 0x109, 0x049, 0x148, 0x019, 0x118, 0x058, 0x00D, 0x10C, 0x04C, 0x01C, // A-J
45 0x103, 0x043, 0x142, 0x013, 0x112, 0x052, 0x007, 0x106, 0x046, 0x016, // K-T
46 0x181, 0x0C1, 0x1C0, 0x091, 0x190, 0x0D0, 0x085, 0x184, 0x0C4, 0x094, // U-*
47 0x0A8, 0x0A2, 0x08A, 0x02A // $-%
50 private static final int ASTERISK_ENCODING = CHARACTER_ENCODINGS[39];
52 private final boolean usingCheckDigit;
53 private final boolean extendedMode;
56 * Creates a reader that assumes all encoded data is data, and does not treat the final
57 * character as a check digit. It will not decoded "extended Code 39" sequences.
59 public Code39Reader() {
60 usingCheckDigit = false;
65 * Creates a reader that can be configured to check the last character as a check digit.
66 * It will not decoded "extended Code 39" sequences.
68 * @param usingCheckDigit if true, treat the last data character as a check digit, not
69 * data, and verify that the checksum passes.
71 public Code39Reader(boolean usingCheckDigit) {
72 this.usingCheckDigit = usingCheckDigit;
73 this.extendedMode = false;
77 * Creates a reader that can be configured to check the last character as a check digit,
78 * or optionally attempt to decode "extended Code 39" sequences that are used to encode
79 * the full ASCII character set.
81 * @param usingCheckDigit if true, treat the last data character as a check digit, not
82 * data, and verify that the checksum passes.
83 * @param extendedMode if true, will attempt to decode extended Code 39 sequences in the
86 public Code39Reader(boolean usingCheckDigit, boolean extendedMode) {
87 this.usingCheckDigit = usingCheckDigit;
88 this.extendedMode = extendedMode;
91 public Result decodeRow(int rowNumber, BitArray row, Hashtable hints) throws ReaderException {
93 int[] start = findAsteriskPattern(row);
94 int nextStart = start[1];
95 int end = row.getSize();
97 // Read off white space
98 while (nextStart < end && !row.get(nextStart)) {
102 StringBuffer result = new StringBuffer();
103 int[] counters = new int[9];
107 recordPattern(row, nextStart, counters);
108 int pattern = toNarrowWidePattern(counters);
109 decodedChar = patternToChar(pattern);
110 result.append(decodedChar);
111 lastStart = nextStart;
112 for (int i = 0; i < counters.length; i++) {
113 nextStart += counters[i];
115 // Read off white space
116 while (nextStart < end && !row.get(nextStart)) {
119 } while (decodedChar != '*');
120 result.deleteCharAt(result.length() - 1); // remove asterisk
122 // Look for whitespace after pattern:
123 int lastPatternSize = 0;
124 for (int i = 0; i < counters.length; i++) {
125 lastPatternSize += counters[i];
127 int whiteSpaceAfterEnd = nextStart - lastStart - lastPatternSize;
128 // If 50% of last pattern size, following last pattern, is not whitespace, fail
129 // (but if it's whitespace to the very end of the image, that's OK)
130 if (nextStart != end && whiteSpaceAfterEnd / 2 < lastPatternSize) {
131 throw ReaderException.getInstance();
134 if (usingCheckDigit) {
135 int max = result.length() - 1;
137 for (int i = 0; i < max; i++) {
138 total += ALPHABET_STRING.indexOf(result.charAt(i));
140 if (total % 43 != ALPHABET_STRING.indexOf(result.charAt(max))) {
141 throw ReaderException.getInstance();
143 result.deleteCharAt(max);
146 String resultString = result.toString();
148 resultString = decodeExtended(resultString);
151 if (resultString.length() == 0) {
152 // Almost surely a false positive
153 throw ReaderException.getInstance();
156 float left = (float) (start[1] + start[0]) / 2.0f;
157 float right = (float) (nextStart + lastStart) / 2.0f;
162 new ResultPoint(left, (float) rowNumber),
163 new ResultPoint(right, (float) rowNumber)},
164 BarcodeFormat.CODE_39);
168 private static int[] findAsteriskPattern(BitArray row) throws ReaderException {
169 int width = row.getSize();
171 while (rowOffset < width) {
172 if (row.get(rowOffset)) {
178 int counterPosition = 0;
179 int[] counters = new int[9];
180 int patternStart = rowOffset;
181 boolean isWhite = false;
182 int patternLength = counters.length;
184 for (int i = rowOffset; i < width; i++) {
185 boolean pixel = row.get(i);
186 if (pixel ^ isWhite) {
187 counters[counterPosition]++;
189 if (counterPosition == patternLength - 1) {
191 if (toNarrowWidePattern(counters) == ASTERISK_ENCODING) {
192 // Look for whitespace before start pattern, >= 50% of width of start pattern
193 if (row.isRange(Math.max(0, patternStart - (i - patternStart) / 2), patternStart, false)) {
194 return new int[]{patternStart, i};
197 } catch (ReaderException re) {
198 // no match, continue
200 patternStart += counters[0] + counters[1];
201 for (int y = 2; y < patternLength; y++) {
202 counters[y - 2] = counters[y];
204 counters[patternLength - 2] = 0;
205 counters[patternLength - 1] = 0;
210 counters[counterPosition] = 1;
211 isWhite ^= true; // isWhite = !isWhite;
214 throw ReaderException.getInstance();
217 private static int toNarrowWidePattern(int[] counters) throws ReaderException {
218 int numCounters = counters.length;
219 int maxNarrowCounter = 0;
222 int minCounter = Integer.MAX_VALUE;
223 for (int i = 0; i < numCounters; i++) {
224 int counter = counters[i];
225 if (counter < minCounter && counter > maxNarrowCounter) {
226 minCounter = counter;
229 maxNarrowCounter = minCounter;
231 int totalWideCountersWidth = 0;
233 for (int i = 0; i < numCounters; i++) {
234 int counter = counters[i];
235 if (counters[i] > maxNarrowCounter) {
236 pattern |= 1 << (numCounters - 1 - i);
238 totalWideCountersWidth += counter;
241 if (wideCounters == 3) {
242 // Found 3 wide counters, but are they close enough in width?
243 // We can perform a cheap, conservative check to see if any individual
244 // counter is more than 1.5 times the average:
245 for (int i = 0; i < numCounters && wideCounters > 0; i++) {
246 int counter = counters[i];
247 if (counters[i] > maxNarrowCounter) {
249 // totalWideCountersWidth = 3 * average, so this checks if counter >= 3/2 * average
250 if ((counter << 1) >= totalWideCountersWidth) {
251 throw ReaderException.getInstance();
257 } while (wideCounters > 3);
258 throw ReaderException.getInstance();
261 private static char patternToChar(int pattern) throws ReaderException {
262 for (int i = 0; i < CHARACTER_ENCODINGS.length; i++) {
263 if (CHARACTER_ENCODINGS[i] == pattern) {
267 throw ReaderException.getInstance();
270 private static String decodeExtended(String encoded) throws ReaderException {
271 int length = encoded.length();
272 StringBuffer decoded = new StringBuffer(length);
273 for (int i = 0; i < length; i++) {
274 char c = encoded.charAt(i);
275 if (c == '+' || c == '$' || c == '%' || c == '/') {
276 char next = encoded.charAt(i + 1);
277 char decodedChar = '\0';
280 // +A to +Z map to a to z
281 if (next >= 'A' && next <= 'Z') {
282 decodedChar = (char) (next + 32);
284 throw ReaderException.getInstance();
288 // $A to $Z map to control codes SH to SB
289 if (next >= 'A' && next <= 'Z') {
290 decodedChar = (char) (next - 64);
292 throw ReaderException.getInstance();
296 // %A to %E map to control codes ESC to US
297 if (next >= 'A' && next <= 'E') {
298 decodedChar = (char) (next - 38);
299 } else if (next >= 'F' && next <= 'W') {
300 decodedChar = (char) (next - 11);
302 throw ReaderException.getInstance();
306 // /A to /O map to ! to , and /Z maps to :
307 if (next >= 'A' && next <= 'O') {
308 decodedChar = (char) (next - 32);
309 } else if (next == 'Z') {
312 throw ReaderException.getInstance();
316 decoded.append(decodedChar);
317 // bump up i again since we read two characters
323 return decoded.toString();