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 OneDReader {
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(20);
103 int[] counters = new int[9];
107 recordPattern(row, nextStart, counters);
108 int pattern = toNarrowWidePattern(counters);
110 throw ReaderException.getInstance();
112 decodedChar = patternToChar(pattern);
113 result.append(decodedChar);
114 lastStart = nextStart;
115 for (int i = 0; i < counters.length; i++) {
116 nextStart += counters[i];
118 // Read off white space
119 while (nextStart < end && !row.get(nextStart)) {
122 } while (decodedChar != '*');
123 result.deleteCharAt(result.length() - 1); // remove asterisk
125 // Look for whitespace after pattern:
126 int lastPatternSize = 0;
127 for (int i = 0; i < counters.length; i++) {
128 lastPatternSize += counters[i];
130 int whiteSpaceAfterEnd = nextStart - lastStart - lastPatternSize;
131 // If 50% of last pattern size, following last pattern, is not whitespace, fail
132 // (but if it's whitespace to the very end of the image, that's OK)
133 if (nextStart != end && whiteSpaceAfterEnd / 2 < lastPatternSize) {
134 throw ReaderException.getInstance();
137 if (usingCheckDigit) {
138 int max = result.length() - 1;
140 for (int i = 0; i < max; i++) {
141 total += ALPHABET_STRING.indexOf(result.charAt(i));
143 if (total % 43 != ALPHABET_STRING.indexOf(result.charAt(max))) {
144 throw ReaderException.getInstance();
146 result.deleteCharAt(max);
149 String resultString = result.toString();
151 resultString = decodeExtended(resultString);
154 if (resultString.length() == 0) {
155 // Almost surely a false positive
156 throw ReaderException.getInstance();
159 float left = (float) (start[1] + start[0]) / 2.0f;
160 float right = (float) (nextStart + lastStart) / 2.0f;
165 new ResultPoint(left, (float) rowNumber),
166 new ResultPoint(right, (float) rowNumber)},
167 BarcodeFormat.CODE_39);
171 private static int[] findAsteriskPattern(BitArray row) throws ReaderException {
172 int width = row.getSize();
174 while (rowOffset < width) {
175 if (row.get(rowOffset)) {
181 int counterPosition = 0;
182 int[] counters = new int[9];
183 int patternStart = rowOffset;
184 boolean isWhite = false;
185 int patternLength = counters.length;
187 for (int i = rowOffset; i < width; i++) {
188 boolean pixel = row.get(i);
189 if (pixel ^ isWhite) {
190 counters[counterPosition]++;
192 if (counterPosition == patternLength - 1) {
193 if (toNarrowWidePattern(counters) == ASTERISK_ENCODING) {
194 // Look for whitespace before start pattern, >= 50% of width of start pattern
195 if (row.isRange(Math.max(0, patternStart - (i - patternStart) / 2), patternStart, false)) {
196 return new int[]{patternStart, i};
199 patternStart += counters[0] + counters[1];
200 for (int y = 2; y < patternLength; y++) {
201 counters[y - 2] = counters[y];
203 counters[patternLength - 2] = 0;
204 counters[patternLength - 1] = 0;
209 counters[counterPosition] = 1;
210 isWhite ^= true; // isWhite = !isWhite;
213 throw ReaderException.getInstance();
216 // For efficiency, returns -1 on failure. Not throwing here saved as many as 700 exceptions
217 // per image when using some of our blackbox images.
218 private static int toNarrowWidePattern(int[] counters) {
219 int numCounters = counters.length;
220 int maxNarrowCounter = 0;
223 int minCounter = Integer.MAX_VALUE;
224 for (int i = 0; i < numCounters; i++) {
225 int counter = counters[i];
226 if (counter < minCounter && counter > maxNarrowCounter) {
227 minCounter = counter;
230 maxNarrowCounter = minCounter;
232 int totalWideCountersWidth = 0;
234 for (int i = 0; i < numCounters; i++) {
235 int counter = counters[i];
236 if (counters[i] > maxNarrowCounter) {
237 pattern |= 1 << (numCounters - 1 - i);
239 totalWideCountersWidth += counter;
242 if (wideCounters == 3) {
243 // Found 3 wide counters, but are they close enough in width?
244 // We can perform a cheap, conservative check to see if any individual
245 // counter is more than 1.5 times the average:
246 for (int i = 0; i < numCounters && wideCounters > 0; i++) {
247 int counter = counters[i];
248 if (counters[i] > maxNarrowCounter) {
250 // totalWideCountersWidth = 3 * average, so this checks if counter >= 3/2 * average
251 if ((counter << 1) >= totalWideCountersWidth) {
258 } while (wideCounters > 3);
262 private static char patternToChar(int pattern) throws ReaderException {
263 for (int i = 0; i < CHARACTER_ENCODINGS.length; i++) {
264 if (CHARACTER_ENCODINGS[i] == pattern) {
268 throw ReaderException.getInstance();
271 private static String decodeExtended(String encoded) throws ReaderException {
272 int length = encoded.length();
273 StringBuffer decoded = new StringBuffer(length);
274 for (int i = 0; i < length; i++) {
275 char c = encoded.charAt(i);
276 if (c == '+' || c == '$' || c == '%' || c == '/') {
277 char next = encoded.charAt(i + 1);
278 char decodedChar = '\0';
281 // +A to +Z map to a to z
282 if (next >= 'A' && next <= 'Z') {
283 decodedChar = (char) (next + 32);
285 throw ReaderException.getInstance();
289 // $A to $Z map to control codes SH to SB
290 if (next >= 'A' && next <= 'Z') {
291 decodedChar = (char) (next - 64);
293 throw ReaderException.getInstance();
297 // %A to %E map to control codes ESC to US
298 if (next >= 'A' && next <= 'E') {
299 decodedChar = (char) (next - 38);
300 } else if (next >= 'F' && next <= 'W') {
301 decodedChar = (char) (next - 11);
303 throw ReaderException.getInstance();
307 // /A to /O map to ! to , and /Z maps to :
308 if (next >= 'A' && next <= 'O') {
309 decodedChar = (char) (next - 32);
310 } else if (next == 'Z') {
313 throw ReaderException.getInstance();
317 decoded.append(decodedChar);
318 // bump up i again since we read two characters
324 return decoded.toString();