code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
/* * Copyright 2008 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.oned; import com.google.zxing.BarcodeFormat; import com.google.zxing.ChecksumException; import com.google.zxing.DecodeHintType; import com.google.zxing.FormatException; import com.google.zxing.NotFoundException; import com.google.zxing.Result; import com.google.zxing.ResultPoint; import com.google.zxing.common.BitArray; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * <p>Decodes Code 128 barcodes.</p> * * @author Sean Owen */ public final class Code128Reader extends OneDReader { static final int[][] CODE_PATTERNS = { {2, 1, 2, 2, 2, 2}, // 0 {2, 2, 2, 1, 2, 2}, {2, 2, 2, 2, 2, 1}, {1, 2, 1, 2, 2, 3}, {1, 2, 1, 3, 2, 2}, {1, 3, 1, 2, 2, 2}, // 5 {1, 2, 2, 2, 1, 3}, {1, 2, 2, 3, 1, 2}, {1, 3, 2, 2, 1, 2}, {2, 2, 1, 2, 1, 3}, {2, 2, 1, 3, 1, 2}, // 10 {2, 3, 1, 2, 1, 2}, {1, 1, 2, 2, 3, 2}, {1, 2, 2, 1, 3, 2}, {1, 2, 2, 2, 3, 1}, {1, 1, 3, 2, 2, 2}, // 15 {1, 2, 3, 1, 2, 2}, {1, 2, 3, 2, 2, 1}, {2, 2, 3, 2, 1, 1}, {2, 2, 1, 1, 3, 2}, {2, 2, 1, 2, 3, 1}, // 20 {2, 1, 3, 2, 1, 2}, {2, 2, 3, 1, 1, 2}, {3, 1, 2, 1, 3, 1}, {3, 1, 1, 2, 2, 2}, {3, 2, 1, 1, 2, 2}, // 25 {3, 2, 1, 2, 2, 1}, {3, 1, 2, 2, 1, 2}, {3, 2, 2, 1, 1, 2}, {3, 2, 2, 2, 1, 1}, {2, 1, 2, 1, 2, 3}, // 30 {2, 1, 2, 3, 2, 1}, {2, 3, 2, 1, 2, 1}, {1, 1, 1, 3, 2, 3}, {1, 3, 1, 1, 2, 3}, {1, 3, 1, 3, 2, 1}, // 35 {1, 1, 2, 3, 1, 3}, {1, 3, 2, 1, 1, 3}, {1, 3, 2, 3, 1, 1}, {2, 1, 1, 3, 1, 3}, {2, 3, 1, 1, 1, 3}, // 40 {2, 3, 1, 3, 1, 1}, {1, 1, 2, 1, 3, 3}, {1, 1, 2, 3, 3, 1}, {1, 3, 2, 1, 3, 1}, {1, 1, 3, 1, 2, 3}, // 45 {1, 1, 3, 3, 2, 1}, {1, 3, 3, 1, 2, 1}, {3, 1, 3, 1, 2, 1}, {2, 1, 1, 3, 3, 1}, {2, 3, 1, 1, 3, 1}, // 50 {2, 1, 3, 1, 1, 3}, {2, 1, 3, 3, 1, 1}, {2, 1, 3, 1, 3, 1}, {3, 1, 1, 1, 2, 3}, {3, 1, 1, 3, 2, 1}, // 55 {3, 3, 1, 1, 2, 1}, {3, 1, 2, 1, 1, 3}, {3, 1, 2, 3, 1, 1}, {3, 3, 2, 1, 1, 1}, {3, 1, 4, 1, 1, 1}, // 60 {2, 2, 1, 4, 1, 1}, {4, 3, 1, 1, 1, 1}, {1, 1, 1, 2, 2, 4}, {1, 1, 1, 4, 2, 2}, {1, 2, 1, 1, 2, 4}, // 65 {1, 2, 1, 4, 2, 1}, {1, 4, 1, 1, 2, 2}, {1, 4, 1, 2, 2, 1}, {1, 1, 2, 2, 1, 4}, {1, 1, 2, 4, 1, 2}, // 70 {1, 2, 2, 1, 1, 4}, {1, 2, 2, 4, 1, 1}, {1, 4, 2, 1, 1, 2}, {1, 4, 2, 2, 1, 1}, {2, 4, 1, 2, 1, 1}, // 75 {2, 2, 1, 1, 1, 4}, {4, 1, 3, 1, 1, 1}, {2, 4, 1, 1, 1, 2}, {1, 3, 4, 1, 1, 1}, {1, 1, 1, 2, 4, 2}, // 80 {1, 2, 1, 1, 4, 2}, {1, 2, 1, 2, 4, 1}, {1, 1, 4, 2, 1, 2}, {1, 2, 4, 1, 1, 2}, {1, 2, 4, 2, 1, 1}, // 85 {4, 1, 1, 2, 1, 2}, {4, 2, 1, 1, 1, 2}, {4, 2, 1, 2, 1, 1}, {2, 1, 2, 1, 4, 1}, {2, 1, 4, 1, 2, 1}, // 90 {4, 1, 2, 1, 2, 1}, {1, 1, 1, 1, 4, 3}, {1, 1, 1, 3, 4, 1}, {1, 3, 1, 1, 4, 1}, {1, 1, 4, 1, 1, 3}, // 95 {1, 1, 4, 3, 1, 1}, {4, 1, 1, 1, 1, 3}, {4, 1, 1, 3, 1, 1}, {1, 1, 3, 1, 4, 1}, {1, 1, 4, 1, 3, 1}, // 100 {3, 1, 1, 1, 4, 1}, {4, 1, 1, 1, 3, 1}, {2, 1, 1, 4, 1, 2}, {2, 1, 1, 2, 1, 4}, {2, 1, 1, 2, 3, 2}, // 105 {2, 3, 3, 1, 1, 1, 2} }; private static final int MAX_AVG_VARIANCE = (int) (PATTERN_MATCH_RESULT_SCALE_FACTOR * 0.25f); private static final int MAX_INDIVIDUAL_VARIANCE = (int) (PATTERN_MATCH_RESULT_SCALE_FACTOR * 0.7f); private static final int CODE_SHIFT = 98; private static final int CODE_CODE_C = 99; private static final int CODE_CODE_B = 100; private static final int CODE_CODE_A = 101; private static final int CODE_FNC_1 = 102; private static final int CODE_FNC_2 = 97; private static final int CODE_FNC_3 = 96; private static final int CODE_FNC_4_A = 101; private static final int CODE_FNC_4_B = 100; private static final int CODE_START_A = 103; private static final int CODE_START_B = 104; private static final int CODE_START_C = 105; private static final int CODE_STOP = 106; private static int[] findStartPattern(BitArray row) throws NotFoundException { int width = row.getSize(); int rowOffset = row.getNextSet(0); int counterPosition = 0; int[] counters = new int[6]; int patternStart = rowOffset; boolean isWhite = false; int patternLength = counters.length; for (int i = rowOffset; i < width; i++) { if (row.get(i) ^ isWhite) { counters[counterPosition]++; } else { if (counterPosition == patternLength - 1) { int bestVariance = MAX_AVG_VARIANCE; int bestMatch = -1; for (int startCode = CODE_START_A; startCode <= CODE_START_C; startCode++) { int variance = patternMatchVariance(counters, CODE_PATTERNS[startCode], MAX_INDIVIDUAL_VARIANCE); if (variance < bestVariance) { bestVariance = variance; bestMatch = startCode; } } // Look for whitespace before start pattern, >= 50% of width of start pattern if (bestMatch >= 0 && row.isRange(Math.max(0, patternStart - (i - patternStart) / 2), patternStart, false)) { return new int[]{patternStart, i, bestMatch}; } patternStart += counters[0] + counters[1]; System.arraycopy(counters, 2, counters, 0, patternLength - 2); counters[patternLength - 2] = 0; counters[patternLength - 1] = 0; counterPosition--; } else { counterPosition++; } counters[counterPosition] = 1; isWhite = !isWhite; } } throw NotFoundException.getNotFoundInstance(); } private static int decodeCode(BitArray row, int[] counters, int rowOffset) throws NotFoundException { recordPattern(row, rowOffset, counters); int bestVariance = MAX_AVG_VARIANCE; // worst variance we'll accept int bestMatch = -1; for (int d = 0; d < CODE_PATTERNS.length; d++) { int[] pattern = CODE_PATTERNS[d]; int variance = patternMatchVariance(counters, pattern, MAX_INDIVIDUAL_VARIANCE); if (variance < bestVariance) { bestVariance = variance; bestMatch = d; } } // TODO We're overlooking the fact that the STOP pattern has 7 values, not 6. if (bestMatch >= 0) { return bestMatch; } else { throw NotFoundException.getNotFoundInstance(); } } @Override public Result decodeRow(int rowNumber, BitArray row, Map<DecodeHintType,?> hints) throws NotFoundException, FormatException, ChecksumException { boolean convertFNC1 = hints != null && hints.containsKey(DecodeHintType.ASSUME_GS1); int[] startPatternInfo = findStartPattern(row); int startCode = startPatternInfo[2]; int codeSet; switch (startCode) { case CODE_START_A: codeSet = CODE_CODE_A; break; case CODE_START_B: codeSet = CODE_CODE_B; break; case CODE_START_C: codeSet = CODE_CODE_C; break; default: throw FormatException.getFormatInstance(); } boolean done = false; boolean isNextShifted = false; StringBuilder result = new StringBuilder(20); List<Byte> rawCodes = new ArrayList<Byte>(20); int lastStart = startPatternInfo[0]; int nextStart = startPatternInfo[1]; int[] counters = new int[6]; int lastCode = 0; int code = 0; int checksumTotal = startCode; int multiplier = 0; boolean lastCharacterWasPrintable = true; while (!done) { boolean unshift = isNextShifted; isNextShifted = false; // Save off last code lastCode = code; // Decode another code from image code = decodeCode(row, counters, nextStart); rawCodes.add((byte) code); // Remember whether the last code was printable or not (excluding CODE_STOP) if (code != CODE_STOP) { lastCharacterWasPrintable = true; } // Add to checksum computation (if not CODE_STOP of course) if (code != CODE_STOP) { multiplier++; checksumTotal += multiplier * code; } // Advance to where the next code will to start lastStart = nextStart; for (int counter : counters) { nextStart += counter; } // Take care of illegal start codes switch (code) { case CODE_START_A: case CODE_START_B: case CODE_START_C: throw FormatException.getFormatInstance(); } switch (codeSet) { case CODE_CODE_A: if (code < 64) { result.append((char) (' ' + code)); } else if (code < 96) { result.append((char) (code - 64)); } else { // Don't let CODE_STOP, which always appears, affect whether whether we think the last // code was printable or not. if (code != CODE_STOP) { lastCharacterWasPrintable = false; } switch (code) { case CODE_FNC_1: if (convertFNC1) { if (result.length() == 0){ // GS1 specification 5.4.3.7. and 5.4.6.4. If the first char after the start code // is FNC1 then this is GS1-128. We add the symbology identifier. result.append("]C1"); } else { // GS1 specification 5.4.7.5. Every subsequent FNC1 is returned as ASCII 29 (GS) result.append((char) 29); } } break; case CODE_FNC_2: case CODE_FNC_3: case CODE_FNC_4_A: // do nothing? break; case CODE_SHIFT: isNextShifted = true; codeSet = CODE_CODE_B; break; case CODE_CODE_B: codeSet = CODE_CODE_B; break; case CODE_CODE_C: codeSet = CODE_CODE_C; break; case CODE_STOP: done = true; break; } } break; case CODE_CODE_B: if (code < 96) { result.append((char) (' ' + code)); } else { if (code != CODE_STOP) { lastCharacterWasPrintable = false; } switch (code) { case CODE_FNC_1: if (convertFNC1) { if (result.length() == 0){ // GS1 specification 5.4.3.7. and 5.4.6.4. If the first char after the start code // is FNC1 then this is GS1-128. We add the symbology identifier. result.append("]C1"); } else { // GS1 specification 5.4.7.5. Every subsequent FNC1 is returned as ASCII 29 (GS) result.append((char) 29); } } break; case CODE_FNC_2: case CODE_FNC_3: case CODE_FNC_4_B: // do nothing? break; case CODE_SHIFT: isNextShifted = true; codeSet = CODE_CODE_A; break; case CODE_CODE_A: codeSet = CODE_CODE_A; break; case CODE_CODE_C: codeSet = CODE_CODE_C; break; case CODE_STOP: done = true; break; } } break; case CODE_CODE_C: if (code < 100) { if (code < 10) { result.append('0'); } result.append(code); } else { if (code != CODE_STOP) { lastCharacterWasPrintable = false; } switch (code) { case CODE_FNC_1: if (convertFNC1) { if (result.length() == 0){ // GS1 specification 5.4.3.7. and 5.4.6.4. If the first char after the start code // is FNC1 then this is GS1-128. We add the symbology identifier. result.append("]C1"); } else { // GS1 specification 5.4.7.5. Every subsequent FNC1 is returned as ASCII 29 (GS) result.append((char) 29); } } break; case CODE_CODE_A: codeSet = CODE_CODE_A; break; case CODE_CODE_B: codeSet = CODE_CODE_B; break; case CODE_STOP: done = true; break; } } break; } // Unshift back to another code set if we were shifted if (unshift) { codeSet = codeSet == CODE_CODE_A ? CODE_CODE_B : CODE_CODE_A; } } // Check for ample whitespace following pattern, but, to do this we first need to remember that // we fudged decoding CODE_STOP since it actually has 7 bars, not 6. There is a black bar left // to read off. Would be slightly better to properly read. Here we just skip it: nextStart = row.getNextUnset(nextStart); if (!row.isRange(nextStart, Math.min(row.getSize(), nextStart + (nextStart - lastStart) / 2), false)) { throw NotFoundException.getNotFoundInstance(); } // Pull out from sum the value of the penultimate check code checksumTotal -= multiplier * lastCode; // lastCode is the checksum then: if (checksumTotal % 103 != lastCode) { throw ChecksumException.getChecksumInstance(); } // Need to pull out the check digits from string int resultLength = result.length(); if (resultLength == 0) { // false positive throw NotFoundException.getNotFoundInstance(); } // Only bother if the result had at least one character, and if the checksum digit happened to // be a printable character. If it was just interpreted as a control code, nothing to remove. if (resultLength > 0 && lastCharacterWasPrintable) { if (codeSet == CODE_CODE_C) { result.delete(resultLength - 2, resultLength); } else { result.delete(resultLength - 1, resultLength); } } float left = (float) (startPatternInfo[1] + startPatternInfo[0]) / 2.0f; float right = (float) (nextStart + lastStart) / 2.0f; int rawCodesSize = rawCodes.size(); byte[] rawBytes = new byte[rawCodesSize]; for (int i = 0; i < rawCodesSize; i++) { rawBytes[i] = rawCodes.get(i); } return new Result( result.toString(), rawBytes, new ResultPoint[]{ new ResultPoint(left, (float) rowNumber), new ResultPoint(right, (float) rowNumber)}, BarcodeFormat.CODE_128); } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/oned/Code128Reader.java
Java
epl
15,833
/* * Copyright 2010 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.oned; import com.google.zxing.BarcodeFormat; import com.google.zxing.EncodeHintType; import com.google.zxing.WriterException; import com.google.zxing.common.BitMatrix; import java.util.ArrayList; import java.util.Collection; import java.util.Map; /** * This object renders a CODE128 code as a {@link BitMatrix}. * * @author erik.barbara@gmail.com (Erik Barbara) */ public final class Code128Writer extends OneDimensionalCodeWriter { private static final int CODE_START_B = 104; private static final int CODE_START_C = 105; private static final int CODE_CODE_B = 100; private static final int CODE_CODE_C = 99; private static final int CODE_STOP = 106; // Dummy characters used to specify control characters in input private static final char ESCAPE_FNC_1 = '\u00f1'; private static final char ESCAPE_FNC_2 = '\u00f2'; private static final char ESCAPE_FNC_3 = '\u00f3'; private static final char ESCAPE_FNC_4 = '\u00f4'; private static final int CODE_FNC_1 = 102; // Code A, Code B, Code C private static final int CODE_FNC_2 = 97; // Code A, Code B private static final int CODE_FNC_3 = 96; // Code A, Code B private static final int CODE_FNC_4_B = 100; // Code B @Override public BitMatrix encode(String contents, BarcodeFormat format, int width, int height, Map<EncodeHintType,?> hints) throws WriterException { if (format != BarcodeFormat.CODE_128) { throw new IllegalArgumentException("Can only encode CODE_128, but got " + format); } return super.encode(contents, format, width, height, hints); } @Override public boolean[] encode(String contents) { int length = contents.length(); // Check length if (length < 1 || length > 80) { throw new IllegalArgumentException( "Contents length should be between 1 and 80 characters, but got " + length); } // Check content for (int i = 0; i < length; i++) { char c = contents.charAt(i); if (c < ' ' || c > '~') { switch (c) { case ESCAPE_FNC_1: case ESCAPE_FNC_2: case ESCAPE_FNC_3: case ESCAPE_FNC_4: break; default: throw new IllegalArgumentException("Bad character in input: " + c); } } } Collection<int[]> patterns = new ArrayList<int[]>(); // temporary storage for patterns int checkSum = 0; int checkWeight = 1; int codeSet = 0; // selected code (CODE_CODE_B or CODE_CODE_C) int position = 0; // position in contents while (position < length) { //Select code to use int requiredDigitCount = codeSet == CODE_CODE_C ? 2 : 4; int newCodeSet; if (isDigits(contents, position, requiredDigitCount)) { newCodeSet = CODE_CODE_C; } else { newCodeSet = CODE_CODE_B; } //Get the pattern index int patternIndex; if (newCodeSet == codeSet) { // Encode the current character if (codeSet == CODE_CODE_B) { patternIndex = contents.charAt(position) - ' '; position += 1; } else { // CODE_CODE_C switch (contents.charAt(position)) { case ESCAPE_FNC_1: patternIndex = CODE_FNC_1; position++; break; case ESCAPE_FNC_2: patternIndex = CODE_FNC_2; position++; break; case ESCAPE_FNC_3: patternIndex = CODE_FNC_3; position++; break; case ESCAPE_FNC_4: patternIndex = CODE_FNC_4_B; // FIXME if this ever outputs Code A position++; break; default: patternIndex = Integer.parseInt(contents.substring(position, position + 2)); position += 2; break; } } } else { // Should we change the current code? // Do we have a code set? if (codeSet == 0) { // No, we don't have a code set if (newCodeSet == CODE_CODE_B) { patternIndex = CODE_START_B; } else { // CODE_CODE_C patternIndex = CODE_START_C; } } else { // Yes, we have a code set patternIndex = newCodeSet; } codeSet = newCodeSet; } // Get the pattern patterns.add(Code128Reader.CODE_PATTERNS[patternIndex]); // Compute checksum checkSum += patternIndex * checkWeight; if (position != 0) { checkWeight++; } } // Compute and append checksum checkSum %= 103; patterns.add(Code128Reader.CODE_PATTERNS[checkSum]); // Append stop code patterns.add(Code128Reader.CODE_PATTERNS[CODE_STOP]); // Compute code width int codeWidth = 0; for (int[] pattern : patterns) { for (int width : pattern) { codeWidth += width; } } // Compute result boolean[] result = new boolean[codeWidth]; int pos = 0; for (int[] pattern : patterns) { pos += appendPattern(result, pos, pattern, true); } return result; } private static boolean isDigits(CharSequence value, int start, int length) { int end = start + length; int last = value.length(); for (int i = start; i < end && i < last; i++) { char c = value.charAt(i); if (c < '0' || c > '9') { if (c != ESCAPE_FNC_1) { return false; } end++; // ignore FNC_1 } } return end <= last; // end > last if we've run out of string } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/oned/Code128Writer.java
Java
epl
6,343
/* * Copyright 2008 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.oned; import com.google.zxing.BarcodeFormat; import com.google.zxing.DecodeHintType; import com.google.zxing.NotFoundException; import com.google.zxing.Reader; import com.google.zxing.ReaderException; import com.google.zxing.Result; import com.google.zxing.common.BitArray; import com.google.zxing.oned.rss.RSS14Reader; import com.google.zxing.oned.rss.expanded.RSSExpandedReader; import java.util.ArrayList; import java.util.Collection; import java.util.Map; /** * @author dswitkin@google.com (Daniel Switkin) * @author Sean Owen */ public final class MultiFormatOneDReader extends OneDReader { private final OneDReader[] readers; public MultiFormatOneDReader(Map<DecodeHintType,?> hints) { @SuppressWarnings("unchecked") Collection<BarcodeFormat> possibleFormats = hints == null ? null : (Collection<BarcodeFormat>) hints.get(DecodeHintType.POSSIBLE_FORMATS); boolean useCode39CheckDigit = hints != null && hints.get(DecodeHintType.ASSUME_CODE_39_CHECK_DIGIT) != null; Collection<OneDReader> readers = new ArrayList<OneDReader>(); if (possibleFormats != null) { if (possibleFormats.contains(BarcodeFormat.EAN_13) || possibleFormats.contains(BarcodeFormat.UPC_A) || possibleFormats.contains(BarcodeFormat.EAN_8) || possibleFormats.contains(BarcodeFormat.UPC_E)) { readers.add(new MultiFormatUPCEANReader(hints)); } if (possibleFormats.contains(BarcodeFormat.CODE_39)) { readers.add(new Code39Reader(useCode39CheckDigit)); } if (possibleFormats.contains(BarcodeFormat.CODE_93)) { readers.add(new Code93Reader()); } if (possibleFormats.contains(BarcodeFormat.CODE_128)) { readers.add(new Code128Reader()); } if (possibleFormats.contains(BarcodeFormat.ITF)) { readers.add(new ITFReader()); } if (possibleFormats.contains(BarcodeFormat.CODABAR)) { readers.add(new CodaBarReader()); } if (possibleFormats.contains(BarcodeFormat.RSS_14)) { readers.add(new RSS14Reader()); } if (possibleFormats.contains(BarcodeFormat.RSS_EXPANDED)){ readers.add(new RSSExpandedReader()); } } if (readers.isEmpty()) { readers.add(new MultiFormatUPCEANReader(hints)); readers.add(new Code39Reader()); readers.add(new CodaBarReader()); readers.add(new Code93Reader()); readers.add(new Code128Reader()); readers.add(new ITFReader()); readers.add(new RSS14Reader()); readers.add(new RSSExpandedReader()); } this.readers = readers.toArray(new OneDReader[readers.size()]); } @Override public Result decodeRow(int rowNumber, BitArray row, Map<DecodeHintType,?> hints) throws NotFoundException { for (OneDReader reader : readers) { try { return reader.decodeRow(rowNumber, row, hints); } catch (ReaderException re) { // continue } } throw NotFoundException.getNotFoundInstance(); } @Override public void reset() { for (Reader reader : readers) { reader.reset(); } } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/oned/MultiFormatOneDReader.java
Java
epl
3,800
/* * Copyright 2009 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.oned; import com.google.zxing.BarcodeFormat; import com.google.zxing.EncodeHintType; import com.google.zxing.FormatException; import com.google.zxing.WriterException; import com.google.zxing.common.BitMatrix; import java.util.Map; /** * This object renders an EAN13 code as a {@link BitMatrix}. * * @author aripollak@gmail.com (Ari Pollak) */ public final class EAN13Writer extends UPCEANWriter { private static final int CODE_WIDTH = 3 + // start guard (7 * 6) + // left bars 5 + // middle guard (7 * 6) + // right bars 3; // end guard @Override public BitMatrix encode(String contents, BarcodeFormat format, int width, int height, Map<EncodeHintType,?> hints) throws WriterException { if (format != BarcodeFormat.EAN_13) { throw new IllegalArgumentException("Can only encode EAN_13, but got " + format); } return super.encode(contents, format, width, height, hints); } @Override public boolean[] encode(String contents) { if (contents.length() != 13) { throw new IllegalArgumentException( "Requested contents should be 13 digits long, but got " + contents.length()); } try { if (!UPCEANReader.checkStandardUPCEANChecksum(contents)) { throw new IllegalArgumentException("Contents do not pass checksum"); } } catch (FormatException ignored) { throw new IllegalArgumentException("Illegal contents"); } int firstDigit = Integer.parseInt(contents.substring(0, 1)); int parities = EAN13Reader.FIRST_DIGIT_ENCODINGS[firstDigit]; boolean[] result = new boolean[CODE_WIDTH]; int pos = 0; pos += appendPattern(result, pos, UPCEANReader.START_END_PATTERN, true); // See {@link #EAN13Reader} for a description of how the first digit & left bars are encoded for (int i = 1; i <= 6; i++) { int digit = Integer.parseInt(contents.substring(i, i + 1)); if ((parities >> (6 - i) & 1) == 1) { digit += 10; } pos += appendPattern(result, pos, UPCEANReader.L_AND_G_PATTERNS[digit], false); } pos += appendPattern(result, pos, UPCEANReader.MIDDLE_PATTERN, false); for (int i = 7; i <= 12; i++) { int digit = Integer.parseInt(contents.substring(i, i + 1)); pos += appendPattern(result, pos, UPCEANReader.L_PATTERNS[digit], true); } pos += appendPattern(result, pos, UPCEANReader.START_END_PATTERN, true); return result; } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/oned/EAN13Writer.java
Java
epl
3,163
/* * Copyright 2010 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.oned; import com.google.zxing.BarcodeFormat; import com.google.zxing.EncodeHintType; import com.google.zxing.Writer; import com.google.zxing.WriterException; import com.google.zxing.common.BitMatrix; import java.util.Map; /** * This object renders a UPC-A code as a {@link BitMatrix}. * * @author qwandor@google.com (Andrew Walbran) */ public final class UPCAWriter implements Writer { private final EAN13Writer subWriter = new EAN13Writer(); @Override public BitMatrix encode(String contents, BarcodeFormat format, int width, int height) throws WriterException { return encode(contents, format, width, height, null); } @Override public BitMatrix encode(String contents, BarcodeFormat format, int width, int height, Map<EncodeHintType,?> hints) throws WriterException { if (format != BarcodeFormat.UPC_A) { throw new IllegalArgumentException("Can only encode UPC-A, but got " + format); } return subWriter.encode(preencode(contents), BarcodeFormat.EAN_13, width, height, hints); } /** * Transform a UPC-A code into the equivalent EAN-13 code, and add a check digit if it is not * already present. */ private static String preencode(String contents) { int length = contents.length(); if (length == 11) { // No check digit present, calculate it and add it int sum = 0; for (int i = 0; i < 11; ++i) { sum += (contents.charAt(i) - '0') * (i % 2 == 0 ? 3 : 1); } contents += (1000 - sum) % 10; } else if (length != 12) { throw new IllegalArgumentException( "Requested contents should be 11 or 12 digits long, but got " + contents.length()); } return '0' + contents; } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/oned/UPCAWriter.java
Java
epl
2,435
/* * Copyright 2010 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.oned; import com.google.zxing.BarcodeFormat; import com.google.zxing.EncodeHintType; import com.google.zxing.WriterException; import com.google.zxing.common.BitMatrix; import java.util.Map; /** * This object renders a CODE39 code as a {@link BitMatrix}. * * @author erik.barbara@gmail.com (Erik Barbara) */ public final class Code39Writer extends OneDimensionalCodeWriter { @Override public BitMatrix encode(String contents, BarcodeFormat format, int width, int height, Map<EncodeHintType,?> hints) throws WriterException { if (format != BarcodeFormat.CODE_39) { throw new IllegalArgumentException("Can only encode CODE_39, but got " + format); } return super.encode(contents, format, width, height, hints); } @Override public boolean[] encode(String contents) { int length = contents.length(); if (length > 80) { throw new IllegalArgumentException( "Requested contents should be less than 80 digits long, but got " + length); } int[] widths = new int[9]; int codeWidth = 24 + 1 + length; for (int i = 0; i < length; i++) { int indexInString = Code39Reader.ALPHABET_STRING.indexOf(contents.charAt(i)); toIntArray(Code39Reader.CHARACTER_ENCODINGS[indexInString], widths); for (int width : widths) { codeWidth += width; } } boolean[] result = new boolean[codeWidth]; toIntArray(Code39Reader.CHARACTER_ENCODINGS[39], widths); int pos = appendPattern(result, 0, widths, true); int[] narrowWhite = {1}; pos += appendPattern(result, pos, narrowWhite, false); //append next character to bytematrix for(int i = length-1; i >= 0; i--) { int indexInString = Code39Reader.ALPHABET_STRING.indexOf(contents.charAt(i)); toIntArray(Code39Reader.CHARACTER_ENCODINGS[indexInString], widths); pos += appendPattern(result, pos, widths, true); pos += appendPattern(result, pos, narrowWhite, false); } toIntArray(Code39Reader.CHARACTER_ENCODINGS[39], widths); pos += appendPattern(result, pos, widths, true); return result; } private static void toIntArray(int a, int[] toReturn) { for (int i = 0; i < 9; i++) { int temp = a & (1 << i); toReturn[i] = temp == 0 ? 1 : 2; } } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/oned/Code39Writer.java
Java
epl
2,993
/* * Copyright 2009 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.oned; /** * <p>Encapsulates functionality and implementation that is common to UPC and EAN families * of one-dimensional barcodes.</p> * * @author aripollak@gmail.com (Ari Pollak) * @author dsbnatut@gmail.com (Kazuki Nishiura) */ public abstract class UPCEANWriter extends OneDimensionalCodeWriter { @Override public int getDefaultMargin() { // Use a different default more appropriate for UPC/EAN return UPCEANReader.START_END_PATTERN.length; } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/oned/UPCEANWriter.java
Java
epl
1,095
/* * Copyright 2011 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.oned; import com.google.zxing.BarcodeFormat; import com.google.zxing.EncodeHintType; import com.google.zxing.Writer; import com.google.zxing.WriterException; import com.google.zxing.common.BitMatrix; import java.util.Map; /** * <p>Encapsulates functionality and implementation that is common to one-dimensional barcodes.</p> * * @author dsbnatut@gmail.com (Kazuki Nishiura) */ public abstract class OneDimensionalCodeWriter implements Writer { @Override public final BitMatrix encode(String contents, BarcodeFormat format, int width, int height) throws WriterException { return encode(contents, format, width, height, null); } /** * Encode the contents following specified format. * {@code width} and {@code height} are required size. This method may return bigger size * {@code BitMatrix} when specified size is too small. The user can set both {@code width} and * {@code height} to zero to get minimum size barcode. If negative value is set to {@code width} * or {@code height}, {@code IllegalArgumentException} is thrown. */ @Override public BitMatrix encode(String contents, BarcodeFormat format, int width, int height, Map<EncodeHintType,?> hints) throws WriterException { if (contents.length() == 0) { throw new IllegalArgumentException("Found empty contents"); } if (width < 0 || height < 0) { throw new IllegalArgumentException("Negative size is not allowed. Input: " + width + 'x' + height); } int sidesMargin = getDefaultMargin(); if (hints != null) { Integer sidesMarginInt = (Integer) hints.get(EncodeHintType.MARGIN); if (sidesMarginInt != null) { sidesMargin = sidesMarginInt; } } boolean[] code = encode(contents); return renderResult(code, width, height, sidesMargin); } /** * @return a byte array of horizontal pixels (0 = white, 1 = black) */ private static BitMatrix renderResult(boolean[] code, int width, int height, int sidesMargin) { int inputWidth = code.length; // Add quiet zone on both sides. int fullWidth = inputWidth + sidesMargin; int outputWidth = Math.max(width, fullWidth); int outputHeight = Math.max(1, height); int multiple = outputWidth / fullWidth; int leftPadding = (outputWidth - (inputWidth * multiple)) / 2; BitMatrix output = new BitMatrix(outputWidth, outputHeight); for (int inputX = 0, outputX = leftPadding; inputX < inputWidth; inputX++, outputX += multiple) { if (code[inputX]) { output.setRegion(outputX, 0, multiple, outputHeight); } } return output; } /** * Appends the given pattern to the target array starting at pos. * * @param startColor starting color - false for white, true for black * @return the number of elements added to target. */ protected static int appendPattern(boolean[] target, int pos, int[] pattern, boolean startColor) { boolean color = startColor; int numAdded = 0; for (int len : pattern) { for (int j = 0; j < len; j++) { target[pos++] = color; } numAdded += len; color = !color; // flip color after each segment } return numAdded; } public int getDefaultMargin() { // CodaBar spec requires a side margin to be more than ten times wider than narrow space. // This seems like a decent idea for a default for all formats. return 10; } /** * Encode the contents to boolean array expression of one-dimensional barcode. * Start code and end code should be included in result, and side margins should not be included. * * @return a {@code boolean[]} of horizontal pixels (false = white, true = black) */ public abstract boolean[] encode(String contents); }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/oned/OneDimensionalCodeWriter.java
Java
epl
4,523
/* * Copyright 2008 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.oned; import com.google.zxing.BarcodeFormat; import com.google.zxing.DecodeHintType; import com.google.zxing.NotFoundException; import com.google.zxing.Result; import com.google.zxing.ResultPoint; import com.google.zxing.common.BitArray; import java.util.Arrays; import java.util.Map; /** * <p>Decodes Codabar barcodes.</p> * * @author Bas Vijfwinkel * @author David Walker */ public final class CodaBarReader extends OneDReader { // These values are critical for determining how permissive the decoding // will be. All stripe sizes must be within the window these define, as // compared to the average stripe size. private static final int MAX_ACCEPTABLE = (int) (PATTERN_MATCH_RESULT_SCALE_FACTOR * 2.0f); private static final int PADDING = (int) (PATTERN_MATCH_RESULT_SCALE_FACTOR * 1.5f); private static final String ALPHABET_STRING = "0123456789-$:/.+ABCD"; static final char[] ALPHABET = ALPHABET_STRING.toCharArray(); /** * These represent the encodings of characters, as patterns of wide and narrow bars. The 7 least-significant bits of * each int correspond to the pattern of wide and narrow, with 1s representing "wide" and 0s representing narrow. */ static final int[] CHARACTER_ENCODINGS = { 0x003, 0x006, 0x009, 0x060, 0x012, 0x042, 0x021, 0x024, 0x030, 0x048, // 0-9 0x00c, 0x018, 0x045, 0x051, 0x054, 0x015, 0x01A, 0x029, 0x00B, 0x00E, // -$:/.+ABCD }; // minimal number of characters that should be present (inclusing start and stop characters) // under normal circumstances this should be set to 3, but can be set higher // as a last-ditch attempt to reduce false positives. private static final int MIN_CHARACTER_LENGTH = 3; // official start and end patterns private static final char[] STARTEND_ENCODING = {'A', 'B', 'C', 'D'}; // some codabar generator allow the codabar string to be closed by every // character. This will cause lots of false positives! // some industries use a checksum standard but this is not part of the original codabar standard // for more information see : http://www.mecsw.com/specs/codabar.html // Keep some instance variables to avoid reallocations private final StringBuilder decodeRowResult; private int[] counters; private int counterLength; public CodaBarReader() { decodeRowResult = new StringBuilder(20); counters = new int[80]; counterLength = 0; } @Override public Result decodeRow(int rowNumber, BitArray row, Map<DecodeHintType,?> hints) throws NotFoundException { Arrays.fill(counters, 0); setCounters(row); int startOffset = findStartPattern(); int nextStart = startOffset; decodeRowResult.setLength(0); do { int charOffset = toNarrowWidePattern(nextStart); if (charOffset == -1) { throw NotFoundException.getNotFoundInstance(); } // Hack: We store the position in the alphabet table into a // StringBuilder, so that we can access the decoded patterns in // validatePattern. We'll translate to the actual characters later. decodeRowResult.append((char)charOffset); nextStart += 8; // Stop as soon as we see the end character. if (decodeRowResult.length() > 1 && arrayContains(STARTEND_ENCODING, ALPHABET[charOffset])) { break; } } while (nextStart < counterLength); // no fixed end pattern so keep on reading while data is available // Look for whitespace after pattern: int trailingWhitespace = counters[nextStart - 1]; int lastPatternSize = 0; for (int i = -8; i < -1; i++) { lastPatternSize += counters[nextStart + i]; } // We need to see whitespace equal to 50% of the last pattern size, // otherwise this is probably a false positive. The exception is if we are // at the end of the row. (I.e. the barcode barely fits.) if (nextStart < counterLength && trailingWhitespace < lastPatternSize / 2) { throw NotFoundException.getNotFoundInstance(); } validatePattern(startOffset); // Translate character table offsets to actual characters. for (int i = 0; i < decodeRowResult.length(); i++) { decodeRowResult.setCharAt(i, ALPHABET[decodeRowResult.charAt(i)]); } // Ensure a valid start and end character char startchar = decodeRowResult.charAt(0); if (!arrayContains(STARTEND_ENCODING, startchar)) { throw NotFoundException.getNotFoundInstance(); } char endchar = decodeRowResult.charAt(decodeRowResult.length() - 1); if (!arrayContains(STARTEND_ENCODING, endchar)) { throw NotFoundException.getNotFoundInstance(); } // remove stop/start characters character and check if a long enough string is contained if (decodeRowResult.length() <= MIN_CHARACTER_LENGTH) { // Almost surely a false positive ( start + stop + at least 1 character) throw NotFoundException.getNotFoundInstance(); } decodeRowResult.deleteCharAt(decodeRowResult.length() - 1); decodeRowResult.deleteCharAt(0); int runningCount = 0; for (int i = 0; i < startOffset; i++) { runningCount += counters[i]; } float left = (float) runningCount; for (int i = startOffset; i < nextStart - 1; i++) { runningCount += counters[i]; } float right = (float) runningCount; return new Result( decodeRowResult.toString(), null, new ResultPoint[]{ new ResultPoint(left, (float) rowNumber), new ResultPoint(right, (float) rowNumber)}, BarcodeFormat.CODABAR); } void validatePattern(int start) throws NotFoundException { // First, sum up the total size of our four categories of stripe sizes; int[] sizes = {0, 0, 0, 0}; int[] counts = {0, 0, 0, 0}; int end = decodeRowResult.length() - 1; // We break out of this loop in the middle, in order to handle // inter-character spaces properly. int pos = start; for (int i = 0; true; i++) { int pattern = CHARACTER_ENCODINGS[decodeRowResult.charAt(i)]; for (int j = 6; j >= 0; j--) { // Even j = bars, while odd j = spaces. Categories 2 and 3 are for // long stripes, while 0 and 1 are for short stripes. int category = (j & 1) + (pattern & 1) * 2; sizes[category] += counters[pos + j]; counts[category]++; pattern >>= 1; } if (i >= end) { break; } // We ignore the inter-character space - it could be of any size. pos += 8; } // Calculate our allowable size thresholds using fixed-point math. int[] maxes = new int[4]; int[] mins = new int[4]; // Define the threshold of acceptability to be the midpoint between the // average small stripe and the average large stripe. No stripe lengths // should be on the "wrong" side of that line. for (int i = 0; i < 2; i++) { mins[i] = 0; // Accept arbitrarily small "short" stripes. mins[i + 2] = ((sizes[i] << INTEGER_MATH_SHIFT) / counts[i] + (sizes[i + 2] << INTEGER_MATH_SHIFT) / counts[i + 2]) >> 1; maxes[i] = mins[i + 2]; maxes[i + 2] = (sizes[i + 2] * MAX_ACCEPTABLE + PADDING) / counts[i + 2]; } // Now verify that all of the stripes are within the thresholds. pos = start; for (int i = 0; true; i++) { int pattern = CHARACTER_ENCODINGS[decodeRowResult.charAt(i)]; for (int j = 6; j >= 0; j--) { // Even j = bars, while odd j = spaces. Categories 2 and 3 are for // long stripes, while 0 and 1 are for short stripes. int category = (j & 1) + (pattern & 1) * 2; int size = counters[pos + j] << INTEGER_MATH_SHIFT; if (size < mins[category] || size > maxes[category]) { throw NotFoundException.getNotFoundInstance(); } pattern >>= 1; } if (i >= end) { break; } pos += 8; } } /** * Records the size of all runs of white and black pixels, starting with white. * This is just like recordPattern, except it records all the counters, and * uses our builtin "counters" member for storage. * @param row row to count from */ private void setCounters(BitArray row) throws NotFoundException { counterLength = 0; // Start from the first white bit. int i = row.getNextUnset(0); int end = row.getSize(); if (i >= end) { throw NotFoundException.getNotFoundInstance(); } boolean isWhite = true; int count = 0; for (; i < end; i++) { if (row.get(i) ^ isWhite) { // that is, exactly one is true count++; } else { counterAppend(count); count = 1; isWhite = !isWhite; } } counterAppend(count); } private void counterAppend(int e) { counters[counterLength] = e; counterLength++; if (counterLength >= counters.length) { int[] temp = new int[counterLength * 2]; System.arraycopy(counters, 0, temp, 0, counterLength); counters = temp; } } private int findStartPattern() throws NotFoundException { for (int i = 1; i < counterLength; i += 2) { int charOffset = toNarrowWidePattern(i); if (charOffset != -1 && arrayContains(STARTEND_ENCODING, ALPHABET[charOffset])) { // Look for whitespace before start pattern, >= 50% of width of start pattern // We make an exception if the whitespace is the first element. int patternSize = 0; for (int j = i; j < i + 7; j++) { patternSize += counters[j]; } if (i == 1 || counters[i-1] >= patternSize / 2) { return i; } } } throw NotFoundException.getNotFoundInstance(); } static boolean arrayContains(char[] array, char key) { if (array != null) { for (char c : array) { if (c == key) { return true; } } } return false; } // Assumes that counters[position] is a bar. private int toNarrowWidePattern(int position) { int end = position + 7; if (end >= counterLength) { return -1; } int[] theCounters = counters; int maxBar = 0; int minBar = Integer.MAX_VALUE; for (int j = position; j < end; j += 2) { int currentCounter = theCounters[j]; if (currentCounter < minBar) { minBar = currentCounter; } if (currentCounter > maxBar) { maxBar = currentCounter; } } int thresholdBar = (minBar + maxBar) / 2; int maxSpace = 0; int minSpace = Integer.MAX_VALUE; for (int j = position + 1; j < end; j += 2) { int currentCounter = theCounters[j]; if (currentCounter < minSpace) { minSpace = currentCounter; } if (currentCounter > maxSpace) { maxSpace = currentCounter; } } int thresholdSpace = (minSpace + maxSpace) / 2; int bitmask = 1 << 7; int pattern = 0; for (int i = 0; i < 7; i++) { int threshold = (i & 1) == 0 ? thresholdBar : thresholdSpace; bitmask >>= 1; if (theCounters[position + i] > threshold) { pattern |= bitmask; } } for (int i = 0; i < CHARACTER_ENCODINGS.length; i++) { if (CHARACTER_ENCODINGS[i] == pattern) { return i; } } return -1; } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/oned/CodaBarReader.java
Java
epl
12,227
/* * Copyright 2010 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.oned; import com.google.zxing.BarcodeFormat; import com.google.zxing.EncodeHintType; import com.google.zxing.WriterException; import com.google.zxing.common.BitMatrix; import java.util.Map; /** * This object renders a ITF code as a {@link BitMatrix}. * * @author erik.barbara@gmail.com (Erik Barbara) */ public final class ITFWriter extends OneDimensionalCodeWriter { private static final int[] START_PATTERN = {1, 1, 1, 1}; private static final int[] END_PATTERN = {3, 1, 1}; @Override public BitMatrix encode(String contents, BarcodeFormat format, int width, int height, Map<EncodeHintType,?> hints) throws WriterException { if (format != BarcodeFormat.ITF) { throw new IllegalArgumentException("Can only encode ITF, but got " + format); } return super.encode(contents, format, width, height, hints); } @Override public boolean[] encode(String contents) { int length = contents.length(); if (length % 2 != 0) { throw new IllegalArgumentException("The lenght of the input should be even"); } if (length > 80) { throw new IllegalArgumentException( "Requested contents should be less than 80 digits long, but got " + length); } boolean[] result = new boolean[9 + 9 * length]; int pos = appendPattern(result, 0, START_PATTERN, true); for (int i = 0; i < length; i += 2) { int one = Character.digit(contents.charAt(i), 10); int two = Character.digit(contents.charAt(i+1), 10); int[] encoding = new int[18]; for (int j = 0; j < 5; j++) { encoding[j << 1] = ITFReader.PATTERNS[one][j]; encoding[(j << 1) + 1] = ITFReader.PATTERNS[two][j]; } pos += appendPattern(result, pos, encoding, true); } appendPattern(result, pos, END_PATTERN, true); return result; } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/oned/ITFWriter.java
Java
epl
2,548
/* * Copyright 2008 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.oned; import com.google.zxing.BarcodeFormat; import com.google.zxing.ChecksumException; import com.google.zxing.DecodeHintType; import com.google.zxing.FormatException; import com.google.zxing.NotFoundException; import com.google.zxing.Result; import com.google.zxing.ResultPoint; import com.google.zxing.common.BitArray; import java.util.Arrays; import java.util.Map; /** * <p>Decodes Code 39 barcodes. This does not support "Full ASCII Code 39" yet.</p> * * @author Sean Owen * @see Code93Reader */ public final class Code39Reader extends OneDReader { static final String ALPHABET_STRING = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. *$/+%"; private static final char[] ALPHABET = ALPHABET_STRING.toCharArray(); /** * These represent the encodings of characters, as patterns of wide and narrow bars. * The 9 least-significant bits of each int correspond to the pattern of wide and narrow, * with 1s representing "wide" and 0s representing narrow. */ static final int[] CHARACTER_ENCODINGS = { 0x034, 0x121, 0x061, 0x160, 0x031, 0x130, 0x070, 0x025, 0x124, 0x064, // 0-9 0x109, 0x049, 0x148, 0x019, 0x118, 0x058, 0x00D, 0x10C, 0x04C, 0x01C, // A-J 0x103, 0x043, 0x142, 0x013, 0x112, 0x052, 0x007, 0x106, 0x046, 0x016, // K-T 0x181, 0x0C1, 0x1C0, 0x091, 0x190, 0x0D0, 0x085, 0x184, 0x0C4, 0x094, // U-* 0x0A8, 0x0A2, 0x08A, 0x02A // $-% }; private static final int ASTERISK_ENCODING = CHARACTER_ENCODINGS[39]; private final boolean usingCheckDigit; private final boolean extendedMode; private final StringBuilder decodeRowResult; private final int[] counters; /** * Creates a reader that assumes all encoded data is data, and does not treat the final * character as a check digit. It will not decoded "extended Code 39" sequences. */ public Code39Reader() { this(false); } /** * Creates a reader that can be configured to check the last character as a check digit. * It will not decoded "extended Code 39" sequences. * * @param usingCheckDigit if true, treat the last data character as a check digit, not * data, and verify that the checksum passes. */ public Code39Reader(boolean usingCheckDigit) { this(usingCheckDigit, false); } /** * Creates a reader that can be configured to check the last character as a check digit, * or optionally attempt to decode "extended Code 39" sequences that are used to encode * the full ASCII character set. * * @param usingCheckDigit if true, treat the last data character as a check digit, not * data, and verify that the checksum passes. * @param extendedMode if true, will attempt to decode extended Code 39 sequences in the * text. */ public Code39Reader(boolean usingCheckDigit, boolean extendedMode) { this.usingCheckDigit = usingCheckDigit; this.extendedMode = extendedMode; decodeRowResult = new StringBuilder(20); counters = new int[9]; } @Override public Result decodeRow(int rowNumber, BitArray row, Map<DecodeHintType,?> hints) throws NotFoundException, ChecksumException, FormatException { int[] theCounters = counters; Arrays.fill(theCounters, 0); StringBuilder result = decodeRowResult; result.setLength(0); int[] start = findAsteriskPattern(row, theCounters); // Read off white space int nextStart = row.getNextSet(start[1]); int end = row.getSize(); char decodedChar; int lastStart; do { recordPattern(row, nextStart, theCounters); int pattern = toNarrowWidePattern(theCounters); if (pattern < 0) { throw NotFoundException.getNotFoundInstance(); } decodedChar = patternToChar(pattern); result.append(decodedChar); lastStart = nextStart; for (int counter : theCounters) { nextStart += counter; } // Read off white space nextStart = row.getNextSet(nextStart); } while (decodedChar != '*'); result.setLength(result.length() - 1); // remove asterisk // Look for whitespace after pattern: int lastPatternSize = 0; for (int counter : theCounters) { lastPatternSize += counter; } int whiteSpaceAfterEnd = nextStart - lastStart - lastPatternSize; // If 50% of last pattern size, following last pattern, is not whitespace, fail // (but if it's whitespace to the very end of the image, that's OK) if (nextStart != end && (whiteSpaceAfterEnd >> 1) < lastPatternSize) { throw NotFoundException.getNotFoundInstance(); } if (usingCheckDigit) { int max = result.length() - 1; int total = 0; for (int i = 0; i < max; i++) { total += ALPHABET_STRING.indexOf(decodeRowResult.charAt(i)); } if (result.charAt(max) != ALPHABET[total % 43]) { throw ChecksumException.getChecksumInstance(); } result.setLength(max); } if (result.length() == 0) { // false positive throw NotFoundException.getNotFoundInstance(); } String resultString; if (extendedMode) { resultString = decodeExtended(result); } else { resultString = result.toString(); } float left = (float) (start[1] + start[0]) / 2.0f; float right = (float) (nextStart + lastStart) / 2.0f; return new Result( resultString, null, new ResultPoint[]{ new ResultPoint(left, (float) rowNumber), new ResultPoint(right, (float) rowNumber)}, BarcodeFormat.CODE_39); } private static int[] findAsteriskPattern(BitArray row, int[] counters) throws NotFoundException { int width = row.getSize(); int rowOffset = row.getNextSet(0); int counterPosition = 0; int patternStart = rowOffset; boolean isWhite = false; int patternLength = counters.length; for (int i = rowOffset; i < width; i++) { if (row.get(i) ^ isWhite) { counters[counterPosition]++; } else { if (counterPosition == patternLength - 1) { // Look for whitespace before start pattern, >= 50% of width of start pattern if (toNarrowWidePattern(counters) == ASTERISK_ENCODING && row.isRange(Math.max(0, patternStart - ((i - patternStart) >> 1)), patternStart, false)) { return new int[]{patternStart, i}; } patternStart += counters[0] + counters[1]; System.arraycopy(counters, 2, counters, 0, patternLength - 2); counters[patternLength - 2] = 0; counters[patternLength - 1] = 0; counterPosition--; } else { counterPosition++; } counters[counterPosition] = 1; isWhite = !isWhite; } } throw NotFoundException.getNotFoundInstance(); } // For efficiency, returns -1 on failure. Not throwing here saved as many as 700 exceptions // per image when using some of our blackbox images. private static int toNarrowWidePattern(int[] counters) { int numCounters = counters.length; int maxNarrowCounter = 0; int wideCounters; do { int minCounter = Integer.MAX_VALUE; for (int counter : counters) { if (counter < minCounter && counter > maxNarrowCounter) { minCounter = counter; } } maxNarrowCounter = minCounter; wideCounters = 0; int totalWideCountersWidth = 0; int pattern = 0; for (int i = 0; i < numCounters; i++) { int counter = counters[i]; if (counter > maxNarrowCounter) { pattern |= 1 << (numCounters - 1 - i); wideCounters++; totalWideCountersWidth += counter; } } if (wideCounters == 3) { // Found 3 wide counters, but are they close enough in width? // We can perform a cheap, conservative check to see if any individual // counter is more than 1.5 times the average: for (int i = 0; i < numCounters && wideCounters > 0; i++) { int counter = counters[i]; if (counter > maxNarrowCounter) { wideCounters--; // totalWideCountersWidth = 3 * average, so this checks if counter >= 3/2 * average if ((counter << 1) >= totalWideCountersWidth) { return -1; } } } return pattern; } } while (wideCounters > 3); return -1; } private static char patternToChar(int pattern) throws NotFoundException { for (int i = 0; i < CHARACTER_ENCODINGS.length; i++) { if (CHARACTER_ENCODINGS[i] == pattern) { return ALPHABET[i]; } } throw NotFoundException.getNotFoundInstance(); } private static String decodeExtended(CharSequence encoded) throws FormatException { int length = encoded.length(); StringBuilder decoded = new StringBuilder(length); for (int i = 0; i < length; i++) { char c = encoded.charAt(i); if (c == '+' || c == '$' || c == '%' || c == '/') { char next = encoded.charAt(i + 1); char decodedChar = '\0'; switch (c) { case '+': // +A to +Z map to a to z if (next >= 'A' && next <= 'Z') { decodedChar = (char) (next + 32); } else { throw FormatException.getFormatInstance(); } break; case '$': // $A to $Z map to control codes SH to SB if (next >= 'A' && next <= 'Z') { decodedChar = (char) (next - 64); } else { throw FormatException.getFormatInstance(); } break; case '%': // %A to %E map to control codes ESC to US if (next >= 'A' && next <= 'E') { decodedChar = (char) (next - 38); } else if (next >= 'F' && next <= 'W') { decodedChar = (char) (next - 11); } else { throw FormatException.getFormatInstance(); } break; case '/': // /A to /O map to ! to , and /Z maps to : if (next >= 'A' && next <= 'O') { decodedChar = (char) (next - 32); } else if (next == 'Z') { decodedChar = ':'; } else { throw FormatException.getFormatInstance(); } break; } decoded.append(decodedChar); // bump up i again since we read two characters i++; } else { decoded.append(c); } } return decoded.toString(); } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/oned/Code39Reader.java
Java
epl
11,137
/* * Copyright 2010 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.oned; import com.google.zxing.BarcodeFormat; import com.google.zxing.ChecksumException; import com.google.zxing.DecodeHintType; import com.google.zxing.FormatException; import com.google.zxing.NotFoundException; import com.google.zxing.Result; import com.google.zxing.ResultPoint; import com.google.zxing.common.BitArray; import java.util.Arrays; import java.util.Map; /** * <p>Decodes Code 93 barcodes.</p> * * @author Sean Owen * @see Code39Reader */ public final class Code93Reader extends OneDReader { // Note that 'abcd' are dummy characters in place of control characters. private static final String ALPHABET_STRING = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. $/+%abcd*"; private static final char[] ALPHABET = ALPHABET_STRING.toCharArray(); /** * These represent the encodings of characters, as patterns of wide and narrow bars. * The 9 least-significant bits of each int correspond to the pattern of wide and narrow. */ private static final int[] CHARACTER_ENCODINGS = { 0x114, 0x148, 0x144, 0x142, 0x128, 0x124, 0x122, 0x150, 0x112, 0x10A, // 0-9 0x1A8, 0x1A4, 0x1A2, 0x194, 0x192, 0x18A, 0x168, 0x164, 0x162, 0x134, // A-J 0x11A, 0x158, 0x14C, 0x146, 0x12C, 0x116, 0x1B4, 0x1B2, 0x1AC, 0x1A6, // K-T 0x196, 0x19A, 0x16C, 0x166, 0x136, 0x13A, // U-Z 0x12E, 0x1D4, 0x1D2, 0x1CA, 0x16E, 0x176, 0x1AE, // - - % 0x126, 0x1DA, 0x1D6, 0x132, 0x15E, // Control chars? $-* }; private static final int ASTERISK_ENCODING = CHARACTER_ENCODINGS[47]; private final StringBuilder decodeRowResult; private final int[] counters; public Code93Reader() { decodeRowResult = new StringBuilder(20); counters = new int[6]; } @Override public Result decodeRow(int rowNumber, BitArray row, Map<DecodeHintType,?> hints) throws NotFoundException, ChecksumException, FormatException { int[] start = findAsteriskPattern(row); // Read off white space int nextStart = row.getNextSet(start[1]); int end = row.getSize(); int[] theCounters = counters; Arrays.fill(theCounters, 0); StringBuilder result = decodeRowResult; result.setLength(0); char decodedChar; int lastStart; do { recordPattern(row, nextStart, theCounters); int pattern = toPattern(theCounters); if (pattern < 0) { throw NotFoundException.getNotFoundInstance(); } decodedChar = patternToChar(pattern); result.append(decodedChar); lastStart = nextStart; for (int counter : theCounters) { nextStart += counter; } // Read off white space nextStart = row.getNextSet(nextStart); } while (decodedChar != '*'); result.deleteCharAt(result.length() - 1); // remove asterisk // Should be at least one more black module if (nextStart == end || !row.get(nextStart)) { throw NotFoundException.getNotFoundInstance(); } if (result.length() < 2) { // false positive -- need at least 2 checksum digits throw NotFoundException.getNotFoundInstance(); } checkChecksums(result); // Remove checksum digits result.setLength(result.length() - 2); String resultString = decodeExtended(result); float left = (float) (start[1] + start[0]) / 2.0f; float right = (float) (nextStart + lastStart) / 2.0f; return new Result( resultString, null, new ResultPoint[]{ new ResultPoint(left, (float) rowNumber), new ResultPoint(right, (float) rowNumber)}, BarcodeFormat.CODE_93); } private int[] findAsteriskPattern(BitArray row) throws NotFoundException { int width = row.getSize(); int rowOffset = row.getNextSet(0); Arrays.fill(counters, 0); int[] theCounters = counters; int patternStart = rowOffset; boolean isWhite = false; int patternLength = theCounters.length; int counterPosition = 0; for (int i = rowOffset; i < width; i++) { if (row.get(i) ^ isWhite) { theCounters[counterPosition]++; } else { if (counterPosition == patternLength - 1) { if (toPattern(theCounters) == ASTERISK_ENCODING) { return new int[]{patternStart, i}; } patternStart += theCounters[0] + theCounters[1]; System.arraycopy(theCounters, 2, theCounters, 0, patternLength - 2); theCounters[patternLength - 2] = 0; theCounters[patternLength - 1] = 0; counterPosition--; } else { counterPosition++; } theCounters[counterPosition] = 1; isWhite = !isWhite; } } throw NotFoundException.getNotFoundInstance(); } private static int toPattern(int[] counters) { int max = counters.length; int sum = 0; for (int counter : counters) { sum += counter; } int pattern = 0; for (int i = 0; i < max; i++) { int scaledShifted = (counters[i] << INTEGER_MATH_SHIFT) * 9 / sum; int scaledUnshifted = scaledShifted >> INTEGER_MATH_SHIFT; if ((scaledShifted & 0xFF) > 0x7F) { scaledUnshifted++; } if (scaledUnshifted < 1 || scaledUnshifted > 4) { return -1; } if ((i & 0x01) == 0) { for (int j = 0; j < scaledUnshifted; j++) { pattern = (pattern << 1) | 0x01; } } else { pattern <<= scaledUnshifted; } } return pattern; } private static char patternToChar(int pattern) throws NotFoundException { for (int i = 0; i < CHARACTER_ENCODINGS.length; i++) { if (CHARACTER_ENCODINGS[i] == pattern) { return ALPHABET[i]; } } throw NotFoundException.getNotFoundInstance(); } private static String decodeExtended(CharSequence encoded) throws FormatException { int length = encoded.length(); StringBuilder decoded = new StringBuilder(length); for (int i = 0; i < length; i++) { char c = encoded.charAt(i); if (c >= 'a' && c <= 'd') { if (i >= length - 1) { throw FormatException.getFormatInstance(); } char next = encoded.charAt(i + 1); char decodedChar = '\0'; switch (c) { case 'd': // +A to +Z map to a to z if (next >= 'A' && next <= 'Z') { decodedChar = (char) (next + 32); } else { throw FormatException.getFormatInstance(); } break; case 'a': // $A to $Z map to control codes SH to SB if (next >= 'A' && next <= 'Z') { decodedChar = (char) (next - 64); } else { throw FormatException.getFormatInstance(); } break; case 'b': // %A to %E map to control codes ESC to US if (next >= 'A' && next <= 'E') { decodedChar = (char) (next - 38); } else if (next >= 'F' && next <= 'W') { decodedChar = (char) (next - 11); } else { throw FormatException.getFormatInstance(); } break; case 'c': // /A to /O map to ! to , and /Z maps to : if (next >= 'A' && next <= 'O') { decodedChar = (char) (next - 32); } else if (next == 'Z') { decodedChar = ':'; } else { throw FormatException.getFormatInstance(); } break; } decoded.append(decodedChar); // bump up i again since we read two characters i++; } else { decoded.append(c); } } return decoded.toString(); } private static void checkChecksums(CharSequence result) throws ChecksumException { int length = result.length(); checkOneChecksum(result, length - 2, 20); checkOneChecksum(result, length - 1, 15); } private static void checkOneChecksum(CharSequence result, int checkPosition, int weightMax) throws ChecksumException { int weight = 1; int total = 0; for (int i = checkPosition - 1; i >= 0; i--) { total += weight * ALPHABET_STRING.indexOf(result.charAt(i)); if (++weight > weightMax) { weight = 1; } } if (result.charAt(checkPosition) != ALPHABET[total % 47]) { throw ChecksumException.getChecksumInstance(); } } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/oned/Code93Reader.java
Java
epl
8,965
/* * Copyright (C) 2010 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.oned; import com.google.zxing.BarcodeFormat; import com.google.zxing.NotFoundException; import com.google.zxing.Result; import com.google.zxing.ResultMetadataType; import com.google.zxing.ResultPoint; import com.google.zxing.common.BitArray; import java.util.EnumMap; import java.util.Map; /** * @see UPCEANExtension2Support */ final class UPCEANExtension5Support { private static final int[] CHECK_DIGIT_ENCODINGS = { 0x18, 0x14, 0x12, 0x11, 0x0C, 0x06, 0x03, 0x0A, 0x09, 0x05 }; private final int[] decodeMiddleCounters = new int[4]; private final StringBuilder decodeRowStringBuffer = new StringBuilder(); Result decodeRow(int rowNumber, BitArray row, int[] extensionStartRange) throws NotFoundException { StringBuilder result = decodeRowStringBuffer; result.setLength(0); int end = decodeMiddle(row, extensionStartRange, result); String resultString = result.toString(); Map<ResultMetadataType,Object> extensionData = parseExtensionString(resultString); Result extensionResult = new Result(resultString, null, new ResultPoint[] { new ResultPoint((extensionStartRange[0] + extensionStartRange[1]) / 2.0f, (float) rowNumber), new ResultPoint((float) end, (float) rowNumber), }, BarcodeFormat.UPC_EAN_EXTENSION); if (extensionData != null) { extensionResult.putAllMetadata(extensionData); } return extensionResult; } int decodeMiddle(BitArray row, int[] startRange, StringBuilder resultString) throws NotFoundException { int[] counters = decodeMiddleCounters; counters[0] = 0; counters[1] = 0; counters[2] = 0; counters[3] = 0; int end = row.getSize(); int rowOffset = startRange[1]; int lgPatternFound = 0; for (int x = 0; x < 5 && rowOffset < end; x++) { int bestMatch = UPCEANReader.decodeDigit(row, counters, rowOffset, UPCEANReader.L_AND_G_PATTERNS); resultString.append((char) ('0' + bestMatch % 10)); for (int counter : counters) { rowOffset += counter; } if (bestMatch >= 10) { lgPatternFound |= 1 << (4 - x); } if (x != 4) { // Read off separator if not last rowOffset = row.getNextSet(rowOffset); rowOffset = row.getNextUnset(rowOffset); } } if (resultString.length() != 5) { throw NotFoundException.getNotFoundInstance(); } int checkDigit = determineCheckDigit(lgPatternFound); if (extensionChecksum(resultString.toString()) != checkDigit) { throw NotFoundException.getNotFoundInstance(); } return rowOffset; } private static int extensionChecksum(CharSequence s) { int length = s.length(); int sum = 0; for (int i = length - 2; i >= 0; i -= 2) { sum += (int) s.charAt(i) - (int) '0'; } sum *= 3; for (int i = length - 1; i >= 0; i -= 2) { sum += (int) s.charAt(i) - (int) '0'; } sum *= 3; return sum % 10; } private static int determineCheckDigit(int lgPatternFound) throws NotFoundException { for (int d = 0; d < 10; d++) { if (lgPatternFound == CHECK_DIGIT_ENCODINGS[d]) { return d; } } throw NotFoundException.getNotFoundInstance(); } /** * @param raw raw content of extension * @return formatted interpretation of raw content as a {@link Map} mapping * one {@link ResultMetadataType} to appropriate value, or {@code null} if not known */ private static Map<ResultMetadataType,Object> parseExtensionString(String raw) { if (raw.length() != 5) { return null; } Object value = parseExtension5String(raw); if (value == null) { return null; } Map<ResultMetadataType,Object> result = new EnumMap<ResultMetadataType,Object>(ResultMetadataType.class); result.put(ResultMetadataType.SUGGESTED_PRICE, value); return result; } private static String parseExtension5String(String raw) { String currency; switch (raw.charAt(0)) { case '0': currency = "£"; break; case '5': currency = "$"; break; case '9': // Reference: http://www.jollytech.com if ("90000".equals(raw)) { // No suggested retail price return null; } if ("99991".equals(raw)) { // Complementary return "0.00"; } if ("99990".equals(raw)) { return "Used"; } // Otherwise... unknown currency? currency = ""; break; default: currency = ""; break; } int rawAmount = Integer.parseInt(raw.substring(1)); String unitsString = String.valueOf(rawAmount / 100); int hundredths = rawAmount % 100; String hundredthsString = hundredths < 10 ? "0" + hundredths : String.valueOf(hundredths); return currency + unitsString + '.' + hundredthsString; } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/oned/UPCEANExtension5Support.java
Java
epl
5,612
/* * Copyright 2008 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.oned; import com.google.zxing.BarcodeFormat; import com.google.zxing.NotFoundException; import com.google.zxing.common.BitArray; /** * <p>Implements decoding of the EAN-8 format.</p> * * @author Sean Owen */ public final class EAN8Reader extends UPCEANReader { private final int[] decodeMiddleCounters; public EAN8Reader() { decodeMiddleCounters = new int[4]; } @Override protected int decodeMiddle(BitArray row, int[] startRange, StringBuilder result) throws NotFoundException { int[] counters = decodeMiddleCounters; counters[0] = 0; counters[1] = 0; counters[2] = 0; counters[3] = 0; int end = row.getSize(); int rowOffset = startRange[1]; for (int x = 0; x < 4 && rowOffset < end; x++) { int bestMatch = decodeDigit(row, counters, rowOffset, L_PATTERNS); result.append((char) ('0' + bestMatch)); for (int counter : counters) { rowOffset += counter; } } int[] middleRange = findGuardPattern(row, rowOffset, true, MIDDLE_PATTERN); rowOffset = middleRange[1]; for (int x = 0; x < 4 && rowOffset < end; x++) { int bestMatch = decodeDigit(row, counters, rowOffset, L_PATTERNS); result.append((char) ('0' + bestMatch)); for (int counter : counters) { rowOffset += counter; } } return rowOffset; } @Override BarcodeFormat getBarcodeFormat() { return BarcodeFormat.EAN_8; } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/oned/EAN8Reader.java
Java
epl
2,115
/* * Copyright 2011 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.oned; import java.util.Arrays; /** * This class renders CodaBar as {@code boolean[]}. * * @author dsbnatut@gmail.com (Kazuki Nishiura) */ public final class CodaBarWriter extends OneDimensionalCodeWriter { private static final char[] START_CHARS = {'A', 'B', 'C', 'D'}; private static final char[] END_CHARS = {'T', 'N', '*', 'E'}; @Override public boolean[] encode(String contents) { // Verify input and calculate decoded length. if (!CodaBarReader.arrayContains(START_CHARS, Character.toUpperCase(contents.charAt(0)))) { throw new IllegalArgumentException( "Codabar should start with one of the following: " + Arrays.toString(START_CHARS)); } if (!CodaBarReader.arrayContains(END_CHARS, Character.toUpperCase(contents.charAt(contents.length() - 1)))) { throw new IllegalArgumentException( "Codabar should end with one of the following: " + Arrays.toString(END_CHARS)); } // The start character and the end character are decoded to 10 length each. int resultLength = 20; char[] charsWhichAreTenLengthEachAfterDecoded = {'/', ':', '+', '.'}; for (int i = 1; i < contents.length() - 1; i++) { if (Character.isDigit(contents.charAt(i)) || contents.charAt(i) == '-' || contents.charAt(i) == '$') { resultLength += 9; } else if (CodaBarReader.arrayContains( charsWhichAreTenLengthEachAfterDecoded, contents.charAt(i))) { resultLength += 10; } else { throw new IllegalArgumentException("Cannot encode : '" + contents.charAt(i) + '\''); } } // A blank is placed between each character. resultLength += contents.length() - 1; boolean[] result = new boolean[resultLength]; int position = 0; for (int index = 0; index < contents.length(); index++) { char c = Character.toUpperCase(contents.charAt(index)); if (index == contents.length() - 1) { // The end chars are not in the CodaBarReader.ALPHABET. switch (c) { case 'T': c = 'A'; break; case 'N': c = 'B'; break; case '*': c = 'C'; break; case 'E': c = 'D'; break; } } int code = 0; for (int i = 0; i < CodaBarReader.ALPHABET.length; i++) { // Found any, because I checked above. if (c == CodaBarReader.ALPHABET[i]) { code = CodaBarReader.CHARACTER_ENCODINGS[i]; break; } } boolean color = true; int counter = 0; int bit = 0; while (bit < 7) { // A character consists of 7 digit. result[position] = color; position++; if (((code >> (6 - bit)) & 1) == 0 || counter == 1) { color = !color; // Flip the color. bit++; counter = 0; } else { counter++; } } if (index < contents.length() - 1) { result[position] = false; position++; } } return result; } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/oned/CodaBarWriter.java
Java
epl
3,683
/* * Copyright 2008 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.oned; import com.google.zxing.BarcodeFormat; import com.google.zxing.ChecksumException; import com.google.zxing.FormatException; import com.google.zxing.NotFoundException; import com.google.zxing.common.BitArray; /** * <p>Implements decoding of the UPC-E format.</p> * <p/> * <p><a href="http://www.barcodeisland.com/upce.phtml">This</a> is a great reference for * UPC-E information.</p> * * @author Sean Owen */ public final class UPCEReader extends UPCEANReader { /** * The pattern that marks the middle, and end, of a UPC-E pattern. * There is no "second half" to a UPC-E barcode. */ private static final int[] MIDDLE_END_PATTERN = {1, 1, 1, 1, 1, 1}; /** * See {@link #L_AND_G_PATTERNS}; these values similarly represent patterns of * even-odd parity encodings of digits that imply both the number system (0 or 1) * used, and the check digit. */ private static final int[][] NUMSYS_AND_CHECK_DIGIT_PATTERNS = { {0x38, 0x34, 0x32, 0x31, 0x2C, 0x26, 0x23, 0x2A, 0x29, 0x25}, {0x07, 0x0B, 0x0D, 0x0E, 0x13, 0x19, 0x1C, 0x15, 0x16, 0x1A} }; private final int[] decodeMiddleCounters; public UPCEReader() { decodeMiddleCounters = new int[4]; } @Override protected int decodeMiddle(BitArray row, int[] startRange, StringBuilder result) throws NotFoundException { int[] counters = decodeMiddleCounters; counters[0] = 0; counters[1] = 0; counters[2] = 0; counters[3] = 0; int end = row.getSize(); int rowOffset = startRange[1]; int lgPatternFound = 0; for (int x = 0; x < 6 && rowOffset < end; x++) { int bestMatch = decodeDigit(row, counters, rowOffset, L_AND_G_PATTERNS); result.append((char) ('0' + bestMatch % 10)); for (int counter : counters) { rowOffset += counter; } if (bestMatch >= 10) { lgPatternFound |= 1 << (5 - x); } } determineNumSysAndCheckDigit(result, lgPatternFound); return rowOffset; } @Override protected int[] decodeEnd(BitArray row, int endStart) throws NotFoundException { return findGuardPattern(row, endStart, true, MIDDLE_END_PATTERN); } @Override protected boolean checkChecksum(String s) throws FormatException, ChecksumException { return super.checkChecksum(convertUPCEtoUPCA(s)); } private static void determineNumSysAndCheckDigit(StringBuilder resultString, int lgPatternFound) throws NotFoundException { for (int numSys = 0; numSys <= 1; numSys++) { for (int d = 0; d < 10; d++) { if (lgPatternFound == NUMSYS_AND_CHECK_DIGIT_PATTERNS[numSys][d]) { resultString.insert(0, (char) ('0' + numSys)); resultString.append((char) ('0' + d)); return; } } } throw NotFoundException.getNotFoundInstance(); } @Override BarcodeFormat getBarcodeFormat() { return BarcodeFormat.UPC_E; } /** * Expands a UPC-E value back into its full, equivalent UPC-A code value. * * @param upce UPC-E code as string of digits * @return equivalent UPC-A code as string of digits */ public static String convertUPCEtoUPCA(String upce) { char[] upceChars = new char[6]; upce.getChars(1, 7, upceChars, 0); StringBuilder result = new StringBuilder(12); result.append(upce.charAt(0)); char lastChar = upceChars[5]; switch (lastChar) { case '0': case '1': case '2': result.append(upceChars, 0, 2); result.append(lastChar); result.append("0000"); result.append(upceChars, 2, 3); break; case '3': result.append(upceChars, 0, 3); result.append("00000"); result.append(upceChars, 3, 2); break; case '4': result.append(upceChars, 0, 4); result.append("00000"); result.append(upceChars[4]); break; default: result.append(upceChars, 0, 5); result.append("0000"); result.append(lastChar); break; } result.append(upce.charAt(7)); return result.toString(); } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/oned/UPCEReader.java
Java
epl
4,698
/* * Copyright 2008 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.oned; import com.google.zxing.BarcodeFormat; import com.google.zxing.BinaryBitmap; import com.google.zxing.ChecksumException; import com.google.zxing.DecodeHintType; import com.google.zxing.FormatException; import com.google.zxing.NotFoundException; import com.google.zxing.Result; import com.google.zxing.common.BitArray; import java.util.Map; /** * <p>Implements decoding of the UPC-A format.</p> * * @author dswitkin@google.com (Daniel Switkin) * @author Sean Owen */ public final class UPCAReader extends UPCEANReader { private final UPCEANReader ean13Reader = new EAN13Reader(); @Override public Result decodeRow(int rowNumber, BitArray row, int[] startGuardRange, Map<DecodeHintType,?> hints) throws NotFoundException, FormatException, ChecksumException { return maybeReturnResult(ean13Reader.decodeRow(rowNumber, row, startGuardRange, hints)); } @Override public Result decodeRow(int rowNumber, BitArray row, Map<DecodeHintType,?> hints) throws NotFoundException, FormatException, ChecksumException { return maybeReturnResult(ean13Reader.decodeRow(rowNumber, row, hints)); } @Override public Result decode(BinaryBitmap image) throws NotFoundException, FormatException { return maybeReturnResult(ean13Reader.decode(image)); } @Override public Result decode(BinaryBitmap image, Map<DecodeHintType,?> hints) throws NotFoundException, FormatException { return maybeReturnResult(ean13Reader.decode(image, hints)); } @Override BarcodeFormat getBarcodeFormat() { return BarcodeFormat.UPC_A; } @Override protected int decodeMiddle(BitArray row, int[] startRange, StringBuilder resultString) throws NotFoundException { return ean13Reader.decodeMiddle(row, startRange, resultString); } private static Result maybeReturnResult(Result result) throws FormatException { String text = result.getText(); if (text.charAt(0) == '0') { return new Result(text.substring(1), null, result.getResultPoints(), BarcodeFormat.UPC_A); } else { throw FormatException.getFormatInstance(); } } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/oned/UPCAReader.java
Java
epl
2,810
/* * Copyright (C) 2010 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.oned; import java.util.ArrayList; import java.util.List; /** * Records EAN prefix to GS1 Member Organization, where the member organization * correlates strongly with a country. This is an imperfect means of identifying * a country of origin by EAN-13 barcode value. See * <a href="http://en.wikipedia.org/wiki/List_of_GS1_country_codes"> * http://en.wikipedia.org/wiki/List_of_GS1_country_codes</a>. * * @author Sean Owen */ final class EANManufacturerOrgSupport { private final List<int[]> ranges = new ArrayList<int[]>(); private final List<String> countryIdentifiers = new ArrayList<String>(); String lookupCountryIdentifier(String productCode) { initIfNeeded(); int prefix = Integer.parseInt(productCode.substring(0, 3)); int max = ranges.size(); for (int i = 0; i < max; i++) { int[] range = ranges.get(i); int start = range[0]; if (prefix < start) { return null; } int end = range.length == 1 ? start : range[1]; if (prefix <= end) { return countryIdentifiers.get(i); } } return null; } private void add(int[] range, String id) { ranges.add(range); countryIdentifiers.add(id); } private synchronized void initIfNeeded() { if (!ranges.isEmpty()) { return; } add(new int[] {0,19}, "US/CA"); add(new int[] {30,39}, "US"); add(new int[] {60,139}, "US/CA"); add(new int[] {300,379}, "FR"); add(new int[] {380}, "BG"); add(new int[] {383}, "SI"); add(new int[] {385}, "HR"); add(new int[] {387}, "BA"); add(new int[] {400,440}, "DE"); add(new int[] {450,459}, "JP"); add(new int[] {460,469}, "RU"); add(new int[] {471}, "TW"); add(new int[] {474}, "EE"); add(new int[] {475}, "LV"); add(new int[] {476}, "AZ"); add(new int[] {477}, "LT"); add(new int[] {478}, "UZ"); add(new int[] {479}, "LK"); add(new int[] {480}, "PH"); add(new int[] {481}, "BY"); add(new int[] {482}, "UA"); add(new int[] {484}, "MD"); add(new int[] {485}, "AM"); add(new int[] {486}, "GE"); add(new int[] {487}, "KZ"); add(new int[] {489}, "HK"); add(new int[] {490,499}, "JP"); add(new int[] {500,509}, "GB"); add(new int[] {520}, "GR"); add(new int[] {528}, "LB"); add(new int[] {529}, "CY"); add(new int[] {531}, "MK"); add(new int[] {535}, "MT"); add(new int[] {539}, "IE"); add(new int[] {540,549}, "BE/LU"); add(new int[] {560}, "PT"); add(new int[] {569}, "IS"); add(new int[] {570,579}, "DK"); add(new int[] {590}, "PL"); add(new int[] {594}, "RO"); add(new int[] {599}, "HU"); add(new int[] {600,601}, "ZA"); add(new int[] {603}, "GH"); add(new int[] {608}, "BH"); add(new int[] {609}, "MU"); add(new int[] {611}, "MA"); add(new int[] {613}, "DZ"); add(new int[] {616}, "KE"); add(new int[] {618}, "CI"); add(new int[] {619}, "TN"); add(new int[] {621}, "SY"); add(new int[] {622}, "EG"); add(new int[] {624}, "LY"); add(new int[] {625}, "JO"); add(new int[] {626}, "IR"); add(new int[] {627}, "KW"); add(new int[] {628}, "SA"); add(new int[] {629}, "AE"); add(new int[] {640,649}, "FI"); add(new int[] {690,695}, "CN"); add(new int[] {700,709}, "NO"); add(new int[] {729}, "IL"); add(new int[] {730,739}, "SE"); add(new int[] {740}, "GT"); add(new int[] {741}, "SV"); add(new int[] {742}, "HN"); add(new int[] {743}, "NI"); add(new int[] {744}, "CR"); add(new int[] {745}, "PA"); add(new int[] {746}, "DO"); add(new int[] {750}, "MX"); add(new int[] {754,755}, "CA"); add(new int[] {759}, "VE"); add(new int[] {760,769}, "CH"); add(new int[] {770}, "CO"); add(new int[] {773}, "UY"); add(new int[] {775}, "PE"); add(new int[] {777}, "BO"); add(new int[] {779}, "AR"); add(new int[] {780}, "CL"); add(new int[] {784}, "PY"); add(new int[] {785}, "PE"); add(new int[] {786}, "EC"); add(new int[] {789,790}, "BR"); add(new int[] {800,839}, "IT"); add(new int[] {840,849}, "ES"); add(new int[] {850}, "CU"); add(new int[] {858}, "SK"); add(new int[] {859}, "CZ"); add(new int[] {860}, "YU"); add(new int[] {865}, "MN"); add(new int[] {867}, "KP"); add(new int[] {868,869}, "TR"); add(new int[] {870,879}, "NL"); add(new int[] {880}, "KR"); add(new int[] {885}, "TH"); add(new int[] {888}, "SG"); add(new int[] {890}, "IN"); add(new int[] {893}, "VN"); add(new int[] {896}, "PK"); add(new int[] {899}, "ID"); add(new int[] {900,919}, "AT"); add(new int[] {930,939}, "AU"); add(new int[] {940,949}, "AZ"); add(new int[] {955}, "MY"); add(new int[] {958}, "MO"); } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/oned/EANManufacturerOrgSupport.java
Java
epl
5,790
/* * Copyright 2008 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.oned; import com.google.zxing.BarcodeFormat; import com.google.zxing.NotFoundException; import com.google.zxing.common.BitArray; /** * <p>Implements decoding of the EAN-13 format.</p> * * @author dswitkin@google.com (Daniel Switkin) * @author Sean Owen * @author alasdair@google.com (Alasdair Mackintosh) */ public final class EAN13Reader extends UPCEANReader { // For an EAN-13 barcode, the first digit is represented by the parities used // to encode the next six digits, according to the table below. For example, // if the barcode is 5 123456 789012 then the value of the first digit is // signified by using odd for '1', even for '2', even for '3', odd for '4', // odd for '5', and even for '6'. See http://en.wikipedia.org/wiki/EAN-13 // // Parity of next 6 digits // Digit 0 1 2 3 4 5 // 0 Odd Odd Odd Odd Odd Odd // 1 Odd Odd Even Odd Even Even // 2 Odd Odd Even Even Odd Even // 3 Odd Odd Even Even Even Odd // 4 Odd Even Odd Odd Even Even // 5 Odd Even Even Odd Odd Even // 6 Odd Even Even Even Odd Odd // 7 Odd Even Odd Even Odd Even // 8 Odd Even Odd Even Even Odd // 9 Odd Even Even Odd Even Odd // // Note that the encoding for '0' uses the same parity as a UPC barcode. Hence // a UPC barcode can be converted to an EAN-13 barcode by prepending a 0. // // The encoding is represented by the following array, which is a bit pattern // using Odd = 0 and Even = 1. For example, 5 is represented by: // // Odd Even Even Odd Odd Even // in binary: // 0 1 1 0 0 1 == 0x19 // static final int[] FIRST_DIGIT_ENCODINGS = { 0x00, 0x0B, 0x0D, 0xE, 0x13, 0x19, 0x1C, 0x15, 0x16, 0x1A }; private final int[] decodeMiddleCounters; public EAN13Reader() { decodeMiddleCounters = new int[4]; } @Override protected int decodeMiddle(BitArray row, int[] startRange, StringBuilder resultString) throws NotFoundException { int[] counters = decodeMiddleCounters; counters[0] = 0; counters[1] = 0; counters[2] = 0; counters[3] = 0; int end = row.getSize(); int rowOffset = startRange[1]; int lgPatternFound = 0; for (int x = 0; x < 6 && rowOffset < end; x++) { int bestMatch = decodeDigit(row, counters, rowOffset, L_AND_G_PATTERNS); resultString.append((char) ('0' + bestMatch % 10)); for (int counter : counters) { rowOffset += counter; } if (bestMatch >= 10) { lgPatternFound |= 1 << (5 - x); } } determineFirstDigit(resultString, lgPatternFound); int[] middleRange = findGuardPattern(row, rowOffset, true, MIDDLE_PATTERN); rowOffset = middleRange[1]; for (int x = 0; x < 6 && rowOffset < end; x++) { int bestMatch = decodeDigit(row, counters, rowOffset, L_PATTERNS); resultString.append((char) ('0' + bestMatch)); for (int counter : counters) { rowOffset += counter; } } return rowOffset; } @Override BarcodeFormat getBarcodeFormat() { return BarcodeFormat.EAN_13; } /** * Based on pattern of odd-even ('L' and 'G') patterns used to encoded the explicitly-encoded * digits in a barcode, determines the implicitly encoded first digit and adds it to the * result string. * * @param resultString string to insert decoded first digit into * @param lgPatternFound int whose bits indicates the pattern of odd/even L/G patterns used to * encode digits * @throws NotFoundException if first digit cannot be determined */ private static void determineFirstDigit(StringBuilder resultString, int lgPatternFound) throws NotFoundException { for (int d = 0; d < 10; d++) { if (lgPatternFound == FIRST_DIGIT_ENCODINGS[d]) { resultString.insert(0, (char) ('0' + d)); return; } } throw NotFoundException.getNotFoundInstance(); } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/oned/EAN13Reader.java
Java
epl
4,784
/* * Copyright 2008 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.oned; import com.google.zxing.BinaryBitmap; import com.google.zxing.ChecksumException; import com.google.zxing.DecodeHintType; import com.google.zxing.FormatException; import com.google.zxing.NotFoundException; import com.google.zxing.Reader; import com.google.zxing.ReaderException; import com.google.zxing.Result; import com.google.zxing.ResultMetadataType; import com.google.zxing.ResultPoint; import com.google.zxing.common.BitArray; import java.util.Arrays; import java.util.EnumMap; import java.util.Map; /** * Encapsulates functionality and implementation that is common to all families * of one-dimensional barcodes. * * @author dswitkin@google.com (Daniel Switkin) * @author Sean Owen */ public abstract class OneDReader implements Reader { protected static final int INTEGER_MATH_SHIFT = 8; protected static final int PATTERN_MATCH_RESULT_SCALE_FACTOR = 1 << INTEGER_MATH_SHIFT; @Override public Result decode(BinaryBitmap image) throws NotFoundException, FormatException { return decode(image, null); } // Note that we don't try rotation without the try harder flag, even if rotation was supported. @Override public Result decode(BinaryBitmap image, Map<DecodeHintType,?> hints) throws NotFoundException, FormatException { try { return doDecode(image, hints); } catch (NotFoundException nfe) { boolean tryHarder = hints != null && hints.containsKey(DecodeHintType.TRY_HARDER); if (tryHarder && image.isRotateSupported()) { BinaryBitmap rotatedImage = image.rotateCounterClockwise(); Result result = doDecode(rotatedImage, hints); // Record that we found it rotated 90 degrees CCW / 270 degrees CW Map<ResultMetadataType,?> metadata = result.getResultMetadata(); int orientation = 270; if (metadata != null && metadata.containsKey(ResultMetadataType.ORIENTATION)) { // But if we found it reversed in doDecode(), add in that result here: orientation = (orientation + (Integer) metadata.get(ResultMetadataType.ORIENTATION)) % 360; } result.putMetadata(ResultMetadataType.ORIENTATION, orientation); // Update result points ResultPoint[] points = result.getResultPoints(); if (points != null) { int height = rotatedImage.getHeight(); for (int i = 0; i < points.length; i++) { points[i] = new ResultPoint(height - points[i].getY() - 1, points[i].getX()); } } return result; } else { throw nfe; } } } @Override public void reset() { // do nothing } /** * We're going to examine rows from the middle outward, searching alternately above and below the * middle, and farther out each time. rowStep is the number of rows between each successive * attempt above and below the middle. So we'd scan row middle, then middle - rowStep, then * middle + rowStep, then middle - (2 * rowStep), etc. * rowStep is bigger as the image is taller, but is always at least 1. We've somewhat arbitrarily * decided that moving up and down by about 1/16 of the image is pretty good; we try more of the * image if "trying harder". * * @param image The image to decode * @param hints Any hints that were requested * @return The contents of the decoded barcode * @throws NotFoundException Any spontaneous errors which occur */ private Result doDecode(BinaryBitmap image, Map<DecodeHintType,?> hints) throws NotFoundException { int width = image.getWidth(); int height = image.getHeight(); BitArray row = new BitArray(width); int middle = height >> 1; boolean tryHarder = hints != null && hints.containsKey(DecodeHintType.TRY_HARDER); int rowStep = Math.max(1, height >> (tryHarder ? 8 : 5)); int maxLines; if (tryHarder) { maxLines = height; // Look at the whole image, not just the center } else { maxLines = 15; // 15 rows spaced 1/32 apart is roughly the middle half of the image } for (int x = 0; x < maxLines; x++) { // Scanning from the middle out. Determine which row we're looking at next: int rowStepsAboveOrBelow = (x + 1) >> 1; boolean isAbove = (x & 0x01) == 0; // i.e. is x even? int rowNumber = middle + rowStep * (isAbove ? rowStepsAboveOrBelow : -rowStepsAboveOrBelow); if (rowNumber < 0 || rowNumber >= height) { // Oops, if we run off the top or bottom, stop break; } // Estimate black point for this row and load it: try { row = image.getBlackRow(rowNumber, row); } catch (NotFoundException ignored) { continue; } // While we have the image data in a BitArray, it's fairly cheap to reverse it in place to // handle decoding upside down barcodes. for (int attempt = 0; attempt < 2; attempt++) { if (attempt == 1) { // trying again? row.reverse(); // reverse the row and continue // This means we will only ever draw result points *once* in the life of this method // since we want to avoid drawing the wrong points after flipping the row, and, // don't want to clutter with noise from every single row scan -- just the scans // that start on the center line. if (hints != null && hints.containsKey(DecodeHintType.NEED_RESULT_POINT_CALLBACK)) { Map<DecodeHintType,Object> newHints = new EnumMap<DecodeHintType,Object>(DecodeHintType.class); newHints.putAll(hints); newHints.remove(DecodeHintType.NEED_RESULT_POINT_CALLBACK); hints = newHints; } } try { // Look for a barcode Result result = decodeRow(rowNumber, row, hints); // We found our barcode if (attempt == 1) { // But it was upside down, so note that result.putMetadata(ResultMetadataType.ORIENTATION, 180); // And remember to flip the result points horizontally. ResultPoint[] points = result.getResultPoints(); if (points != null) { points[0] = new ResultPoint(width - points[0].getX() - 1, points[0].getY()); points[1] = new ResultPoint(width - points[1].getX() - 1, points[1].getY()); } } return result; } catch (ReaderException re) { // continue -- just couldn't decode this row } } } throw NotFoundException.getNotFoundInstance(); } /** * Records the size of successive runs of white and black pixels in a row, starting at a given point. * The values are recorded in the given array, and the number of runs recorded is equal to the size * of the array. If the row starts on a white pixel at the given start point, then the first count * recorded is the run of white pixels starting from that point; likewise it is the count of a run * of black pixels if the row begin on a black pixels at that point. * * @param row row to count from * @param start offset into row to start at * @param counters array into which to record counts * @throws NotFoundException if counters cannot be filled entirely from row before running out * of pixels */ protected static void recordPattern(BitArray row, int start, int[] counters) throws NotFoundException { int numCounters = counters.length; Arrays.fill(counters, 0, numCounters, 0); int end = row.getSize(); if (start >= end) { throw NotFoundException.getNotFoundInstance(); } boolean isWhite = !row.get(start); int counterPosition = 0; int i = start; while (i < end) { if (row.get(i) ^ isWhite) { // that is, exactly one is true counters[counterPosition]++; } else { counterPosition++; if (counterPosition == numCounters) { break; } else { counters[counterPosition] = 1; isWhite = !isWhite; } } i++; } // If we read fully the last section of pixels and filled up our counters -- or filled // the last counter but ran off the side of the image, OK. Otherwise, a problem. if (!(counterPosition == numCounters || (counterPosition == numCounters - 1 && i == end))) { throw NotFoundException.getNotFoundInstance(); } } protected static void recordPatternInReverse(BitArray row, int start, int[] counters) throws NotFoundException { // This could be more efficient I guess int numTransitionsLeft = counters.length; boolean last = row.get(start); while (start > 0 && numTransitionsLeft >= 0) { if (row.get(--start) != last) { numTransitionsLeft--; last = !last; } } if (numTransitionsLeft >= 0) { throw NotFoundException.getNotFoundInstance(); } recordPattern(row, start + 1, counters); } /** * Determines how closely a set of observed counts of runs of black/white values matches a given * target pattern. This is reported as the ratio of the total variance from the expected pattern * proportions across all pattern elements, to the length of the pattern. * * @param counters observed counters * @param pattern expected pattern * @param maxIndividualVariance The most any counter can differ before we give up * @return ratio of total variance between counters and pattern compared to total pattern size, * where the ratio has been multiplied by 256. So, 0 means no variance (perfect match); 256 means * the total variance between counters and patterns equals the pattern length, higher values mean * even more variance */ protected static int patternMatchVariance(int[] counters, int[] pattern, int maxIndividualVariance) { int numCounters = counters.length; int total = 0; int patternLength = 0; for (int i = 0; i < numCounters; i++) { total += counters[i]; patternLength += pattern[i]; } if (total < patternLength) { // If we don't even have one pixel per unit of bar width, assume this is too small // to reliably match, so fail: return Integer.MAX_VALUE; } // We're going to fake floating-point math in integers. We just need to use more bits. // Scale up patternLength so that intermediate values below like scaledCounter will have // more "significant digits" int unitBarWidth = (total << INTEGER_MATH_SHIFT) / patternLength; maxIndividualVariance = (maxIndividualVariance * unitBarWidth) >> INTEGER_MATH_SHIFT; int totalVariance = 0; for (int x = 0; x < numCounters; x++) { int counter = counters[x] << INTEGER_MATH_SHIFT; int scaledPattern = pattern[x] * unitBarWidth; int variance = counter > scaledPattern ? counter - scaledPattern : scaledPattern - counter; if (variance > maxIndividualVariance) { return Integer.MAX_VALUE; } totalVariance += variance; } return totalVariance / total; } /** * <p>Attempts to decode a one-dimensional barcode format given a single row of * an image.</p> * * @param rowNumber row number from top of the row * @param row the black/white pixel data of the row * @param hints decode hints * @return {@link Result} containing encoded string and start/end of barcode * @throws NotFoundException if an error occurs or barcode cannot be found */ public abstract Result decodeRow(int rowNumber, BitArray row, Map<DecodeHintType,?> hints) throws NotFoundException, ChecksumException, FormatException; }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/oned/OneDReader.java
Java
epl
12,406
/* * Copyright 2009 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.oned.rss; public class DataCharacter { private final int value; private final int checksumPortion; public DataCharacter(int value, int checksumPortion) { this.value = value; this.checksumPortion = checksumPortion; } public final int getValue() { return value; } public final int getChecksumPortion() { return checksumPortion; } @Override public final String toString() { return value + "(" + checksumPortion + ')'; } @Override public final boolean equals(Object o) { if(!(o instanceof DataCharacter)) { return false; } DataCharacter that = (DataCharacter) o; return value == that.value && checksumPortion == that.checksumPortion; } @Override public final int hashCode() { return value ^ checksumPortion; } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/oned/rss/DataCharacter.java
Java
epl
1,423
/* * Copyright 2009 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.oned.rss; final class Pair extends DataCharacter { private final FinderPattern finderPattern; private int count; Pair(int value, int checksumPortion, FinderPattern finderPattern) { super(value, checksumPortion); this.finderPattern = finderPattern; } FinderPattern getFinderPattern() { return finderPattern; } int getCount() { return count; } void incrementCount() { count++; } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/oned/rss/Pair.java
Java
epl
1,049
/* * Copyright (C) 2010 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.oned.rss; import com.google.zxing.NotFoundException; import com.google.zxing.oned.OneDReader; public abstract class AbstractRSSReader extends OneDReader { private static final int MAX_AVG_VARIANCE = (int) (PATTERN_MATCH_RESULT_SCALE_FACTOR * 0.2f); private static final int MAX_INDIVIDUAL_VARIANCE = (int) (PATTERN_MATCH_RESULT_SCALE_FACTOR * 0.45f); private static final float MIN_FINDER_PATTERN_RATIO = 9.5f / 12.0f; private static final float MAX_FINDER_PATTERN_RATIO = 12.5f / 14.0f; private final int[] decodeFinderCounters; private final int[] dataCharacterCounters; private final float[] oddRoundingErrors; private final float[] evenRoundingErrors; private final int[] oddCounts; private final int[] evenCounts; protected AbstractRSSReader(){ decodeFinderCounters = new int[4]; dataCharacterCounters = new int[8]; oddRoundingErrors = new float[4]; evenRoundingErrors = new float[4]; oddCounts = new int[dataCharacterCounters.length / 2]; evenCounts = new int[dataCharacterCounters.length / 2]; } protected final int[] getDecodeFinderCounters() { return decodeFinderCounters; } protected final int[] getDataCharacterCounters() { return dataCharacterCounters; } protected final float[] getOddRoundingErrors() { return oddRoundingErrors; } protected final float[] getEvenRoundingErrors() { return evenRoundingErrors; } protected final int[] getOddCounts() { return oddCounts; } protected final int[] getEvenCounts() { return evenCounts; } protected static int parseFinderValue(int[] counters, int[][] finderPatterns) throws NotFoundException { for (int value = 0; value < finderPatterns.length; value++) { if (patternMatchVariance(counters, finderPatterns[value], MAX_INDIVIDUAL_VARIANCE) < MAX_AVG_VARIANCE) { return value; } } throw NotFoundException.getNotFoundInstance(); } protected static int count(int[] array) { int count = 0; for (int a : array) { count += a; } return count; } protected static void increment(int[] array, float[] errors) { int index = 0; float biggestError = errors[0]; for (int i = 1; i < array.length; i++) { if (errors[i] > biggestError) { biggestError = errors[i]; index = i; } } array[index]++; } protected static void decrement(int[] array, float[] errors) { int index = 0; float biggestError = errors[0]; for (int i = 1; i < array.length; i++) { if (errors[i] < biggestError) { biggestError = errors[i]; index = i; } } array[index]--; } protected static boolean isFinderPattern(int[] counters) { int firstTwoSum = counters[0] + counters[1]; int sum = firstTwoSum + counters[2] + counters[3]; float ratio = (float) firstTwoSum / (float) sum; if (ratio >= MIN_FINDER_PATTERN_RATIO && ratio <= MAX_FINDER_PATTERN_RATIO) { // passes ratio test in spec, but see if the counts are unreasonable int minCounter = Integer.MAX_VALUE; int maxCounter = Integer.MIN_VALUE; for (int counter : counters) { if (counter > maxCounter) { maxCounter = counter; } if (counter < minCounter) { minCounter = counter; } } return maxCounter < 10 * minCounter; } return false; } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/oned/rss/AbstractRSSReader.java
Java
epl
4,065
/* * Copyright 2009 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.oned.rss; import com.google.zxing.BarcodeFormat; import com.google.zxing.DecodeHintType; import com.google.zxing.NotFoundException; import com.google.zxing.Result; import com.google.zxing.ResultPoint; import com.google.zxing.ResultPointCallback; import com.google.zxing.common.BitArray; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; /** * Decodes RSS-14, including truncated and stacked variants. See ISO/IEC 24724:2006. */ public final class RSS14Reader extends AbstractRSSReader { private static final int[] OUTSIDE_EVEN_TOTAL_SUBSET = {1,10,34,70,126}; private static final int[] INSIDE_ODD_TOTAL_SUBSET = {4,20,48,81}; private static final int[] OUTSIDE_GSUM = {0,161,961,2015,2715}; private static final int[] INSIDE_GSUM = {0,336,1036,1516}; private static final int[] OUTSIDE_ODD_WIDEST = {8,6,4,3,1}; private static final int[] INSIDE_ODD_WIDEST = {2,4,6,8}; private static final int[][] FINDER_PATTERNS = { {3,8,2,1}, {3,5,5,1}, {3,3,7,1}, {3,1,9,1}, {2,7,4,1}, {2,5,6,1}, {2,3,8,1}, {1,5,7,1}, {1,3,9,1}, }; private final List<Pair> possibleLeftPairs; private final List<Pair> possibleRightPairs; public RSS14Reader() { possibleLeftPairs = new ArrayList<Pair>(); possibleRightPairs = new ArrayList<Pair>(); } @Override public Result decodeRow(int rowNumber, BitArray row, Map<DecodeHintType,?> hints) throws NotFoundException { Pair leftPair = decodePair(row, false, rowNumber, hints); addOrTally(possibleLeftPairs, leftPair); row.reverse(); Pair rightPair = decodePair(row, true, rowNumber, hints); addOrTally(possibleRightPairs, rightPair); row.reverse(); int lefSize = possibleLeftPairs.size(); for (int i = 0; i < lefSize; i++) { Pair left = possibleLeftPairs.get(i); if (left.getCount() > 1) { int rightSize = possibleRightPairs.size(); for (int j = 0; j < rightSize; j++) { Pair right = possibleRightPairs.get(j); if (right.getCount() > 1) { if (checkChecksum(left, right)) { return constructResult(left, right); } } } } } throw NotFoundException.getNotFoundInstance(); } private static void addOrTally(Collection<Pair> possiblePairs, Pair pair) { if (pair == null) { return; } boolean found = false; for (Pair other : possiblePairs) { if (other.getValue() == pair.getValue()) { other.incrementCount(); found = true; break; } } if (!found) { possiblePairs.add(pair); } } @Override public void reset() { possibleLeftPairs.clear(); possibleRightPairs.clear(); } private static Result constructResult(Pair leftPair, Pair rightPair) { long symbolValue = 4537077L * leftPair.getValue() + rightPair.getValue(); String text = String.valueOf(symbolValue); StringBuilder buffer = new StringBuilder(14); for (int i = 13 - text.length(); i > 0; i--) { buffer.append('0'); } buffer.append(text); int checkDigit = 0; for (int i = 0; i < 13; i++) { int digit = buffer.charAt(i) - '0'; checkDigit += (i & 0x01) == 0 ? 3 * digit : digit; } checkDigit = 10 - (checkDigit % 10); if (checkDigit == 10) { checkDigit = 0; } buffer.append(checkDigit); ResultPoint[] leftPoints = leftPair.getFinderPattern().getResultPoints(); ResultPoint[] rightPoints = rightPair.getFinderPattern().getResultPoints(); return new Result( String.valueOf(buffer.toString()), null, new ResultPoint[] { leftPoints[0], leftPoints[1], rightPoints[0], rightPoints[1], }, BarcodeFormat.RSS_14); } private static boolean checkChecksum(Pair leftPair, Pair rightPair) { //int leftFPValue = leftPair.getFinderPattern().getValue(); //int rightFPValue = rightPair.getFinderPattern().getValue(); //if ((leftFPValue == 0 && rightFPValue == 8) || // (leftFPValue == 8 && rightFPValue == 0)) { //} int checkValue = (leftPair.getChecksumPortion() + 16 * rightPair.getChecksumPortion()) % 79; int targetCheckValue = 9 * leftPair.getFinderPattern().getValue() + rightPair.getFinderPattern().getValue(); if (targetCheckValue > 72) { targetCheckValue--; } if (targetCheckValue > 8) { targetCheckValue--; } return checkValue == targetCheckValue; } private Pair decodePair(BitArray row, boolean right, int rowNumber, Map<DecodeHintType,?> hints) { try { int[] startEnd = findFinderPattern(row, 0, right); FinderPattern pattern = parseFoundFinderPattern(row, rowNumber, right, startEnd); ResultPointCallback resultPointCallback = hints == null ? null : (ResultPointCallback) hints.get(DecodeHintType.NEED_RESULT_POINT_CALLBACK); if (resultPointCallback != null) { float center = (startEnd[0] + startEnd[1]) / 2.0f; if (right) { // row is actually reversed center = row.getSize() - 1 - center; } resultPointCallback.foundPossibleResultPoint(new ResultPoint(center, rowNumber)); } DataCharacter outside = decodeDataCharacter(row, pattern, true); DataCharacter inside = decodeDataCharacter(row, pattern, false); return new Pair(1597 * outside.getValue() + inside.getValue(), outside.getChecksumPortion() + 4 * inside.getChecksumPortion(), pattern); } catch (NotFoundException ignored) { return null; } } private DataCharacter decodeDataCharacter(BitArray row, FinderPattern pattern, boolean outsideChar) throws NotFoundException { int[] counters = getDataCharacterCounters(); counters[0] = 0; counters[1] = 0; counters[2] = 0; counters[3] = 0; counters[4] = 0; counters[5] = 0; counters[6] = 0; counters[7] = 0; if (outsideChar) { recordPatternInReverse(row, pattern.getStartEnd()[0], counters); } else { recordPattern(row, pattern.getStartEnd()[1] + 1, counters); // reverse it for (int i = 0, j = counters.length - 1; i < j; i++, j--) { int temp = counters[i]; counters[i] = counters[j]; counters[j] = temp; } } int numModules = outsideChar ? 16 : 15; float elementWidth = (float) count(counters) / (float) numModules; int[] oddCounts = this.getOddCounts(); int[] evenCounts = this.getEvenCounts(); float[] oddRoundingErrors = this.getOddRoundingErrors(); float[] evenRoundingErrors = this.getEvenRoundingErrors(); for (int i = 0; i < counters.length; i++) { float value = (float) counters[i] / elementWidth; int count = (int) (value + 0.5f); // Round if (count < 1) { count = 1; } else if (count > 8) { count = 8; } int offset = i >> 1; if ((i & 0x01) == 0) { oddCounts[offset] = count; oddRoundingErrors[offset] = value - count; } else { evenCounts[offset] = count; evenRoundingErrors[offset] = value - count; } } adjustOddEvenCounts(outsideChar, numModules); int oddSum = 0; int oddChecksumPortion = 0; for (int i = oddCounts.length - 1; i >= 0; i--) { oddChecksumPortion *= 9; oddChecksumPortion += oddCounts[i]; oddSum += oddCounts[i]; } int evenChecksumPortion = 0; int evenSum = 0; for (int i = evenCounts.length - 1; i >= 0; i--) { evenChecksumPortion *= 9; evenChecksumPortion += evenCounts[i]; evenSum += evenCounts[i]; } int checksumPortion = oddChecksumPortion + 3*evenChecksumPortion; if (outsideChar) { if ((oddSum & 0x01) != 0 || oddSum > 12 || oddSum < 4) { throw NotFoundException.getNotFoundInstance(); } int group = (12 - oddSum) / 2; int oddWidest = OUTSIDE_ODD_WIDEST[group]; int evenWidest = 9 - oddWidest; int vOdd = RSSUtils.getRSSvalue(oddCounts, oddWidest, false); int vEven = RSSUtils.getRSSvalue(evenCounts, evenWidest, true); int tEven = OUTSIDE_EVEN_TOTAL_SUBSET[group]; int gSum = OUTSIDE_GSUM[group]; return new DataCharacter(vOdd * tEven + vEven + gSum, checksumPortion); } else { if ((evenSum & 0x01) != 0 || evenSum > 10 || evenSum < 4) { throw NotFoundException.getNotFoundInstance(); } int group = (10 - evenSum) / 2; int oddWidest = INSIDE_ODD_WIDEST[group]; int evenWidest = 9 - oddWidest; int vOdd = RSSUtils.getRSSvalue(oddCounts, oddWidest, true); int vEven = RSSUtils.getRSSvalue(evenCounts, evenWidest, false); int tOdd = INSIDE_ODD_TOTAL_SUBSET[group]; int gSum = INSIDE_GSUM[group]; return new DataCharacter(vEven * tOdd + vOdd + gSum, checksumPortion); } } private int[] findFinderPattern(BitArray row, int rowOffset, boolean rightFinderPattern) throws NotFoundException { int[] counters = getDecodeFinderCounters(); counters[0] = 0; counters[1] = 0; counters[2] = 0; counters[3] = 0; int width = row.getSize(); boolean isWhite = false; while (rowOffset < width) { isWhite = !row.get(rowOffset); if (rightFinderPattern == isWhite) { // Will encounter white first when searching for right finder pattern break; } rowOffset++; } int counterPosition = 0; int patternStart = rowOffset; for (int x = rowOffset; x < width; x++) { if (row.get(x) ^ isWhite) { counters[counterPosition]++; } else { if (counterPosition == 3) { if (isFinderPattern(counters)) { return new int[]{patternStart, x}; } patternStart += counters[0] + counters[1]; counters[0] = counters[2]; counters[1] = counters[3]; counters[2] = 0; counters[3] = 0; counterPosition--; } else { counterPosition++; } counters[counterPosition] = 1; isWhite = !isWhite; } } throw NotFoundException.getNotFoundInstance(); } private FinderPattern parseFoundFinderPattern(BitArray row, int rowNumber, boolean right, int[] startEnd) throws NotFoundException { // Actually we found elements 2-5 boolean firstIsBlack = row.get(startEnd[0]); int firstElementStart = startEnd[0] - 1; // Locate element 1 while (firstElementStart >= 0 && firstIsBlack ^ row.get(firstElementStart)) { firstElementStart--; } firstElementStart++; int firstCounter = startEnd[0] - firstElementStart; // Make 'counters' hold 1-4 int[] counters = getDecodeFinderCounters(); System.arraycopy(counters, 0, counters, 1, counters.length - 1); counters[0] = firstCounter; int value = parseFinderValue(counters, FINDER_PATTERNS); int start = firstElementStart; int end = startEnd[1]; if (right) { // row is actually reversed start = row.getSize() - 1 - start; end = row.getSize() - 1 - end; } return new FinderPattern(value, new int[] {firstElementStart, startEnd[1]}, start, end, rowNumber); } private void adjustOddEvenCounts(boolean outsideChar, int numModules) throws NotFoundException { int oddSum = count(getOddCounts()); int evenSum = count(getEvenCounts()); int mismatch = oddSum + evenSum - numModules; boolean oddParityBad = (oddSum & 0x01) == (outsideChar ? 1 : 0); boolean evenParityBad = (evenSum & 0x01) == 1; boolean incrementOdd = false; boolean decrementOdd = false; boolean incrementEven = false; boolean decrementEven = false; if (outsideChar) { if (oddSum > 12) { decrementOdd = true; } else if (oddSum < 4) { incrementOdd = true; } if (evenSum > 12) { decrementEven = true; } else if (evenSum < 4) { incrementEven = true; } } else { if (oddSum > 11) { decrementOdd = true; } else if (oddSum < 5) { incrementOdd = true; } if (evenSum > 10) { decrementEven = true; } else if (evenSum < 4) { incrementEven = true; } } /*if (mismatch == 2) { if (!(oddParityBad && evenParityBad)) { throw ReaderException.getInstance(); } decrementOdd = true; decrementEven = true; } else if (mismatch == -2) { if (!(oddParityBad && evenParityBad)) { throw ReaderException.getInstance(); } incrementOdd = true; incrementEven = true; } else */if (mismatch == 1) { if (oddParityBad) { if (evenParityBad) { throw NotFoundException.getNotFoundInstance(); } decrementOdd = true; } else { if (!evenParityBad) { throw NotFoundException.getNotFoundInstance(); } decrementEven = true; } } else if (mismatch == -1) { if (oddParityBad) { if (evenParityBad) { throw NotFoundException.getNotFoundInstance(); } incrementOdd = true; } else { if (!evenParityBad) { throw NotFoundException.getNotFoundInstance(); } incrementEven = true; } } else if (mismatch == 0) { if (oddParityBad) { if (!evenParityBad) { throw NotFoundException.getNotFoundInstance(); } // Both bad if (oddSum < evenSum) { incrementOdd = true; decrementEven = true; } else { decrementOdd = true; incrementEven = true; } } else { if (evenParityBad) { throw NotFoundException.getNotFoundInstance(); } // Nothing to do! } } else { throw NotFoundException.getNotFoundInstance(); } if (incrementOdd) { if (decrementOdd) { throw NotFoundException.getNotFoundInstance(); } increment(getOddCounts(), getOddRoundingErrors()); } if (decrementOdd) { decrement(getOddCounts(), getOddRoundingErrors()); } if (incrementEven) { if (decrementEven) { throw NotFoundException.getNotFoundInstance(); } increment(getEvenCounts(), getOddRoundingErrors()); } if (decrementEven) { decrement(getEvenCounts(), getEvenRoundingErrors()); } } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/oned/rss/RSS14Reader.java
Java
epl
15,118
/* * Copyright (C) 2010 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * These authors would like to acknowledge the Spanish Ministry of Industry, * Tourism and Trade, for the support in the project TSI020301-2008-2 * "PIRAmIDE: Personalizable Interactions with Resources on AmI-enabled * Mobile Dynamic Environments", led by Treelogic * ( http://www.treelogic.com/ ): * * http://www.piramidepse.com/ */ package com.google.zxing.oned.rss.expanded; import com.google.zxing.common.BitArray; import java.util.List; /** * @author Pablo Orduña, University of Deusto (pablo.orduna@deusto.es) * @author Eduardo Castillejo, University of Deusto (eduardo.castillejo@deusto.es) */ final class BitArrayBuilder { private BitArrayBuilder() { } static BitArray buildBitArray(List<ExpandedPair> pairs) { int charNumber = (pairs.size() << 1) - 1; if (pairs.get(pairs.size() - 1).getRightChar() == null) { charNumber -= 1; } int size = 12 * charNumber; BitArray binary = new BitArray(size); int accPos = 0; ExpandedPair firstPair = pairs.get(0); int firstValue = firstPair.getRightChar().getValue(); for(int i = 11; i >= 0; --i){ if ((firstValue & (1 << i)) != 0) { binary.set(accPos); } accPos++; } for(int i = 1; i < pairs.size(); ++i){ ExpandedPair currentPair = pairs.get(i); int leftValue = currentPair.getLeftChar().getValue(); for(int j = 11; j >= 0; --j){ if ((leftValue & (1 << j)) != 0) { binary.set(accPos); } accPos++; } if(currentPair.getRightChar() != null){ int rightValue = currentPair.getRightChar().getValue(); for(int j = 11; j >= 0; --j){ if ((rightValue & (1 << j)) != 0) { binary.set(accPos); } accPos++; } } } return binary; } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/oned/rss/expanded/BitArrayBuilder.java
Java
epl
2,424
/* * Copyright (C) 2010 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * These authors would like to acknowledge the Spanish Ministry of Industry, * Tourism and Trade, for the support in the project TSI020301-2008-2 * "PIRAmIDE: Personalizable Interactions with Resources on AmI-enabled * Mobile Dynamic Environments", led by Treelogic * ( http://www.treelogic.com/ ): * * http://www.piramidepse.com/ */ package com.google.zxing.oned.rss.expanded; import com.google.zxing.oned.rss.DataCharacter; import com.google.zxing.oned.rss.FinderPattern; /** * @author Pablo Orduña, University of Deusto (pablo.orduna@deusto.es) */ final class ExpandedPair { private final boolean mayBeLast; private final DataCharacter leftChar; private final DataCharacter rightChar; private final FinderPattern finderPattern; ExpandedPair(DataCharacter leftChar, DataCharacter rightChar, FinderPattern finderPattern, boolean mayBeLast) { this.leftChar = leftChar; this.rightChar = rightChar; this.finderPattern = finderPattern; this.mayBeLast = mayBeLast; } boolean mayBeLast(){ return this.mayBeLast; } DataCharacter getLeftChar() { return this.leftChar; } DataCharacter getRightChar() { return this.rightChar; } FinderPattern getFinderPattern() { return this.finderPattern; } public boolean mustBeLast() { return this.rightChar == null; } @Override public String toString() { return "[ " + leftChar + " , " + rightChar + " : " + (finderPattern == null ? "null" : finderPattern.getValue()) + " ]"; } @Override public boolean equals(Object o) { if (!(o instanceof ExpandedPair)) { return false; } ExpandedPair that = (ExpandedPair) o; return equalsOrNull(leftChar, that.leftChar) && equalsOrNull(rightChar, that.rightChar) && equalsOrNull(finderPattern, that.finderPattern); } private static boolean equalsOrNull(Object o1, Object o2) { return o1 == null ? o2 == null : o1.equals(o2); } @Override public int hashCode() { return hashNotNull(leftChar) ^ hashNotNull(rightChar) ^ hashNotNull(finderPattern); } private static int hashNotNull(Object o) { return o == null ? 0 : o.hashCode(); } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/oned/rss/expanded/ExpandedPair.java
Java
epl
2,851
/* * Copyright (C) 2010 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * These authors would like to acknowledge the Spanish Ministry of Industry, * Tourism and Trade, for the support in the project TSI020301-2008-2 * "PIRAmIDE: Personalizable Interactions with Resources on AmI-enabled * Mobile Dynamic Environments", led by Treelogic * ( http://www.treelogic.com/ ): * * http://www.piramidepse.com/ */ package com.google.zxing.oned.rss.expanded; import com.google.zxing.BarcodeFormat; import com.google.zxing.DecodeHintType; import com.google.zxing.NotFoundException; import com.google.zxing.Result; import com.google.zxing.ResultPoint; import com.google.zxing.common.BitArray; import com.google.zxing.oned.rss.AbstractRSSReader; import com.google.zxing.oned.rss.DataCharacter; import com.google.zxing.oned.rss.FinderPattern; import com.google.zxing.oned.rss.RSSUtils; import com.google.zxing.oned.rss.expanded.decoders.AbstractExpandedDecoder; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Collections; /** * @author Pablo Orduña, University of Deusto (pablo.orduna@deusto.es) * @author Eduardo Castillejo, University of Deusto (eduardo.castillejo@deusto.es) */ public final class RSSExpandedReader extends AbstractRSSReader { private static final int[] SYMBOL_WIDEST = {7, 5, 4, 3, 1}; private static final int[] EVEN_TOTAL_SUBSET = {4, 20, 52, 104, 204}; private static final int[] GSUM = {0, 348, 1388, 2948, 3988}; private static final int[][] FINDER_PATTERNS = { {1,8,4,1}, // A {3,6,4,1}, // B {3,4,6,1}, // C {3,2,8,1}, // D {2,6,5,1}, // E {2,2,9,1} // F }; private static final int[][] WEIGHTS = { { 1, 3, 9, 27, 81, 32, 96, 77}, { 20, 60, 180, 118, 143, 7, 21, 63}, {189, 145, 13, 39, 117, 140, 209, 205}, {193, 157, 49, 147, 19, 57, 171, 91}, { 62, 186, 136, 197, 169, 85, 44, 132}, {185, 133, 188, 142, 4, 12, 36, 108}, {113, 128, 173, 97, 80, 29, 87, 50}, {150, 28, 84, 41, 123, 158, 52, 156}, { 46, 138, 203, 187, 139, 206, 196, 166}, { 76, 17, 51, 153, 37, 111, 122, 155}, { 43, 129, 176, 106, 107, 110, 119, 146}, { 16, 48, 144, 10, 30, 90, 59, 177}, {109, 116, 137, 200, 178, 112, 125, 164}, { 70, 210, 208, 202, 184, 130, 179, 115}, {134, 191, 151, 31, 93, 68, 204, 190}, {148, 22, 66, 198, 172, 94, 71, 2}, { 6, 18, 54, 162, 64, 192,154, 40}, {120, 149, 25, 75, 14, 42,126, 167}, { 79, 26, 78, 23, 69, 207,199, 175}, {103, 98, 83, 38, 114, 131, 182, 124}, {161, 61, 183, 127, 170, 88, 53, 159}, { 55, 165, 73, 8, 24, 72, 5, 15}, { 45, 135, 194, 160, 58, 174, 100, 89} }; private static final int FINDER_PAT_A = 0; private static final int FINDER_PAT_B = 1; private static final int FINDER_PAT_C = 2; private static final int FINDER_PAT_D = 3; private static final int FINDER_PAT_E = 4; private static final int FINDER_PAT_F = 5; private static final int[][] FINDER_PATTERN_SEQUENCES = { { FINDER_PAT_A, FINDER_PAT_A }, { FINDER_PAT_A, FINDER_PAT_B, FINDER_PAT_B }, { FINDER_PAT_A, FINDER_PAT_C, FINDER_PAT_B, FINDER_PAT_D }, { FINDER_PAT_A, FINDER_PAT_E, FINDER_PAT_B, FINDER_PAT_D, FINDER_PAT_C }, { FINDER_PAT_A, FINDER_PAT_E, FINDER_PAT_B, FINDER_PAT_D, FINDER_PAT_D, FINDER_PAT_F }, { FINDER_PAT_A, FINDER_PAT_E, FINDER_PAT_B, FINDER_PAT_D, FINDER_PAT_E, FINDER_PAT_F, FINDER_PAT_F }, { FINDER_PAT_A, FINDER_PAT_A, FINDER_PAT_B, FINDER_PAT_B, FINDER_PAT_C, FINDER_PAT_C, FINDER_PAT_D, FINDER_PAT_D }, { FINDER_PAT_A, FINDER_PAT_A, FINDER_PAT_B, FINDER_PAT_B, FINDER_PAT_C, FINDER_PAT_C, FINDER_PAT_D, FINDER_PAT_E, FINDER_PAT_E }, { FINDER_PAT_A, FINDER_PAT_A, FINDER_PAT_B, FINDER_PAT_B, FINDER_PAT_C, FINDER_PAT_C, FINDER_PAT_D, FINDER_PAT_E, FINDER_PAT_F, FINDER_PAT_F }, { FINDER_PAT_A, FINDER_PAT_A, FINDER_PAT_B, FINDER_PAT_B, FINDER_PAT_C, FINDER_PAT_D, FINDER_PAT_D, FINDER_PAT_E, FINDER_PAT_E, FINDER_PAT_F, FINDER_PAT_F }, }; //private static final int LONGEST_SEQUENCE_SIZE = FINDER_PATTERN_SEQUENCES[FINDER_PATTERN_SEQUENCES.length - 1].length; private static final int MAX_PAIRS = 11; private final List<ExpandedPair> pairs = new ArrayList<ExpandedPair>(MAX_PAIRS); private final List<ExpandedRow> rows = new ArrayList<ExpandedRow>(); private final int [] startEnd = new int[2]; //private final int [] currentSequence = new int[LONGEST_SEQUENCE_SIZE]; private boolean startFromEven = false; @Override public Result decodeRow(int rowNumber, BitArray row, Map<DecodeHintType,?> hints) throws NotFoundException { // Rows can start with even pattern in case in prev rows there where odd number of patters. // So lets try twice this.pairs.clear(); this.startFromEven = false; try { List<ExpandedPair> pairs = decodeRow2pairs(rowNumber, row); return constructResult(pairs); } catch (NotFoundException e) { // OK } this.pairs.clear(); this.startFromEven = true; List<ExpandedPair> pairs = decodeRow2pairs(rowNumber, row); return constructResult(pairs); } @Override public void reset() { this.pairs.clear(); this.rows.clear(); } // Not private for testing List<ExpandedPair> decodeRow2pairs(int rowNumber, BitArray row) throws NotFoundException { try { while (true){ ExpandedPair nextPair = retrieveNextPair(row, this.pairs, rowNumber); this.pairs.add(nextPair); //System.out.println(this.pairs.size()+" pairs found so far on row "+rowNumber+": "+this.pairs); // exit this loop when retrieveNextPair() fails and throws } } catch (NotFoundException nfe) { if (this.pairs.isEmpty()) { throw nfe; } } // TODO: verify sequence of finder patterns as in checkPairSequence() if (checkChecksum()) { return this.pairs; } boolean tryStackedDecode = !this.rows.isEmpty(); boolean wasReversed = false; // TODO: deal with reversed rows storeRow(rowNumber, wasReversed); if (tryStackedDecode) { // When the image is 180-rotated, then rows are sorted in wrong dirrection. // Try twice with both the directions. List<ExpandedPair> ps = checkRows(false); if (ps != null) { return ps; } ps = checkRows(true); if (ps != null) { return ps; } } throw NotFoundException.getNotFoundInstance(); } private List<ExpandedPair> checkRows(boolean reverse) { // Limit number of rows we are checking // We use recursive algorithm with pure complexity and don't want it to take forever // Stacked barcode can have up to 11 rows, so 25 seems resonable enough if (this.rows.size() > 25) { this.rows.clear(); // We will never have a chance to get result, so clear it return null; } this.pairs.clear(); if (reverse) { Collections.reverse(this.rows); } List<ExpandedPair> ps = null; try { ps = checkRows(new ArrayList<ExpandedRow>(), 0); } catch (NotFoundException e) { // OK } if (reverse) { Collections.reverse(this.rows); } return ps; } // Try to construct a valid rows sequence // Recursion is used to implement backtracking private List<ExpandedPair> checkRows(List<ExpandedRow> collectedRows, int currentRow) throws NotFoundException { for (int i = currentRow; i < rows.size(); i++) { ExpandedRow row = rows.get(i); this.pairs.clear(); int size = collectedRows.size(); for (int j = 0; j < size; j++) { this.pairs.addAll(collectedRows.get(j).getPairs()); } this.pairs.addAll(row.getPairs()); if (!isValidSequence(this.pairs)) { continue; } if (checkChecksum()) { return this.pairs; } List<ExpandedRow> rs = new ArrayList<ExpandedRow>(); rs.addAll(collectedRows); rs.add(row); try { // Recursion: try to add more rows return checkRows(rs, i + 1); } catch (NotFoundException e) { // We failed, try the next candidate } } throw NotFoundException.getNotFoundInstance(); } // Whether the pairs form a valid find pattern seqience, // either complete or a prefix private static boolean isValidSequence(List<ExpandedPair> pairs) { for (int[] sequence : FINDER_PATTERN_SEQUENCES) { if (pairs.size() > sequence.length) { continue; } boolean stop = true; for (int j = 0; j < pairs.size(); j++) { if (pairs.get(j).getFinderPattern().getValue() != sequence[j]) { stop = false; break; } } if (stop) { return true; } } return false; } private void storeRow(int rowNumber, boolean wasReversed) { // Discard if duplicate above or below; otherwise insert in order by row number. int insertPos = 0; boolean prevIsSame = false; boolean nextIsSame = false; while (insertPos < this.rows.size()) { ExpandedRow erow = this.rows.get(insertPos); if (erow.getRowNumber() > rowNumber) { nextIsSame = erow.isEquivalent(this.pairs); break; } prevIsSame = erow.isEquivalent(this.pairs); insertPos++; } if (nextIsSame || prevIsSame) { return; } // When the row was partially decoded (e.g. 2 pairs found instead of 3), // it will prevent us from detecting the barcode. // Try to merge partial rows // Check whether the row is part of an allready detected row if (isPartialRow(this.pairs, this.rows)) { return; } this.rows.add(insertPos, new ExpandedRow(this.pairs, rowNumber, wasReversed)); removePartialRows(this.pairs, this.rows); } // Remove all the rows that contains only specified pairs private static void removePartialRows(List<ExpandedPair> pairs, List<ExpandedRow> rows) { for (Iterator<ExpandedRow> iterator = rows.iterator(); iterator.hasNext(); ) { ExpandedRow r = iterator.next(); if (r.getPairs().size() == pairs.size()) { continue; } boolean allFound = true; for (ExpandedPair p : r.getPairs()) { boolean found = false; for (ExpandedPair pp : pairs) { if (p.equals(pp)) { found = true; break; } } if (!found) { allFound = false; break; } } if (allFound) { // 'pairs' contains all the pairs from the row 'r' iterator.remove(); } } } // Returns true when one of the rows already contains all the pairs private static boolean isPartialRow(Iterable<ExpandedPair> pairs, Iterable<ExpandedRow> rows) { for (ExpandedRow r : rows) { boolean allFound = true; for (ExpandedPair p : pairs) { boolean found = false; for (ExpandedPair pp : r.getPairs()) { if (p.equals(pp)) { found = true; break; } } if (!found) { allFound = false; break; } } if (allFound) { // the row 'r' contain all the pairs from 'pairs' return true; } } return false; } // Only used for unit testing List<ExpandedRow> getRows() { return this.rows; } // Not private for unit testing static Result constructResult(List<ExpandedPair> pairs) throws NotFoundException{ BitArray binary = BitArrayBuilder.buildBitArray(pairs); AbstractExpandedDecoder decoder = AbstractExpandedDecoder.createDecoder(binary); String resultingString = decoder.parseInformation(); ResultPoint[] firstPoints = pairs.get(0).getFinderPattern().getResultPoints(); ResultPoint[] lastPoints = pairs.get(pairs.size() - 1).getFinderPattern().getResultPoints(); return new Result( resultingString, null, new ResultPoint[]{firstPoints[0], firstPoints[1], lastPoints[0], lastPoints[1]}, BarcodeFormat.RSS_EXPANDED ); } private boolean checkChecksum() { ExpandedPair firstPair = this.pairs.get(0); DataCharacter checkCharacter = firstPair.getLeftChar(); DataCharacter firstCharacter = firstPair.getRightChar(); if (firstCharacter == null) { return false; } int checksum = firstCharacter.getChecksumPortion(); int s = 2; for(int i = 1; i < this.pairs.size(); ++i){ ExpandedPair currentPair = this.pairs.get(i); checksum += currentPair.getLeftChar().getChecksumPortion(); s++; DataCharacter currentRightChar = currentPair.getRightChar(); if (currentRightChar != null) { checksum += currentRightChar.getChecksumPortion(); s++; } } checksum %= 211; int checkCharacterValue = 211 * (s - 4) + checksum; return checkCharacterValue == checkCharacter.getValue(); } private static int getNextSecondBar(BitArray row, int initialPos){ int currentPos; if (row.get(initialPos)) { currentPos = row.getNextUnset(initialPos); currentPos = row.getNextSet(currentPos); } else { currentPos = row.getNextSet(initialPos); currentPos = row.getNextUnset(currentPos); } return currentPos; } // not private for testing ExpandedPair retrieveNextPair(BitArray row, List<ExpandedPair> previousPairs, int rowNumber) throws NotFoundException { boolean isOddPattern = previousPairs.size() % 2 == 0; if (startFromEven) { isOddPattern = !isOddPattern; } FinderPattern pattern; boolean keepFinding = true; int forcedOffset = -1; do{ this.findNextPair(row, previousPairs, forcedOffset); pattern = parseFoundFinderPattern(row, rowNumber, isOddPattern); if (pattern == null){ forcedOffset = getNextSecondBar(row, this.startEnd[0]); } else { keepFinding = false; } }while(keepFinding); // When stacked symbol is split over multiple rows, there's no way to guess if this pair can be last or not. // boolean mayBeLast = checkPairSequence(previousPairs, pattern); DataCharacter leftChar = this.decodeDataCharacter(row, pattern, isOddPattern, true); if (!previousPairs.isEmpty() && previousPairs.get(previousPairs.size()-1).mustBeLast()) { throw NotFoundException.getNotFoundInstance(); } DataCharacter rightChar; try { rightChar = this.decodeDataCharacter(row, pattern, isOddPattern, false); } catch(NotFoundException ignored) { rightChar = null; } boolean mayBeLast = true; return new ExpandedPair(leftChar, rightChar, pattern, mayBeLast); } private void findNextPair(BitArray row, List<ExpandedPair> previousPairs, int forcedOffset) throws NotFoundException { int[] counters = this.getDecodeFinderCounters(); counters[0] = 0; counters[1] = 0; counters[2] = 0; counters[3] = 0; int width = row.getSize(); int rowOffset; if (forcedOffset >= 0) { rowOffset = forcedOffset; } else if (previousPairs.isEmpty()) { rowOffset = 0; } else{ ExpandedPair lastPair = previousPairs.get(previousPairs.size() - 1); rowOffset = lastPair.getFinderPattern().getStartEnd()[1]; } boolean searchingEvenPair = previousPairs.size() % 2 != 0; if (startFromEven) { searchingEvenPair = !searchingEvenPair; } boolean isWhite = false; while (rowOffset < width) { isWhite = !row.get(rowOffset); if (!isWhite) { break; } rowOffset++; } int counterPosition = 0; int patternStart = rowOffset; for (int x = rowOffset; x < width; x++) { if (row.get(x) ^ isWhite) { counters[counterPosition]++; } else { if (counterPosition == 3) { if (searchingEvenPair) { reverseCounters(counters); } if (isFinderPattern(counters)){ this.startEnd[0] = patternStart; this.startEnd[1] = x; return; } if (searchingEvenPair) { reverseCounters(counters); } patternStart += counters[0] + counters[1]; counters[0] = counters[2]; counters[1] = counters[3]; counters[2] = 0; counters[3] = 0; counterPosition--; } else { counterPosition++; } counters[counterPosition] = 1; isWhite = !isWhite; } } throw NotFoundException.getNotFoundInstance(); } private static void reverseCounters(int [] counters){ int length = counters.length; for(int i = 0; i < length / 2; ++i){ int tmp = counters[i]; counters[i] = counters[length - i - 1]; counters[length - i - 1] = tmp; } } private FinderPattern parseFoundFinderPattern(BitArray row, int rowNumber, boolean oddPattern) { // Actually we found elements 2-5. int firstCounter; int start; int end; if(oddPattern){ // If pattern number is odd, we need to locate element 1 *before* the current block. int firstElementStart = this.startEnd[0] - 1; // Locate element 1 while (firstElementStart >= 0 && !row.get(firstElementStart)) { firstElementStart--; } firstElementStart++; firstCounter = this.startEnd[0] - firstElementStart; start = firstElementStart; end = this.startEnd[1]; }else{ // If pattern number is even, the pattern is reversed, so we need to locate element 1 *after* the current block. start = this.startEnd[0]; end = row.getNextUnset(this.startEnd[1] + 1); firstCounter = end - this.startEnd[1]; } // Make 'counters' hold 1-4 int [] counters = this.getDecodeFinderCounters(); System.arraycopy(counters, 0, counters, 1, counters.length - 1); counters[0] = firstCounter; int value; try { value = parseFinderValue(counters, FINDER_PATTERNS); } catch (NotFoundException ignored) { return null; } return new FinderPattern(value, new int[] {start, end}, start, end, rowNumber); } DataCharacter decodeDataCharacter(BitArray row, FinderPattern pattern, boolean isOddPattern, boolean leftChar) throws NotFoundException { int[] counters = this.getDataCharacterCounters(); counters[0] = 0; counters[1] = 0; counters[2] = 0; counters[3] = 0; counters[4] = 0; counters[5] = 0; counters[6] = 0; counters[7] = 0; if (leftChar) { recordPatternInReverse(row, pattern.getStartEnd()[0], counters); } else { recordPattern(row, pattern.getStartEnd()[1], counters); // reverse it for (int i = 0, j = counters.length - 1; i < j; i++, j--) { int temp = counters[i]; counters[i] = counters[j]; counters[j] = temp; } }//counters[] has the pixels of the module int numModules = 17; //left and right data characters have all the same length float elementWidth = (float) count(counters) / (float) numModules; // Sanity check: element width for pattern and the character should match float expectedElementWidth = (pattern.getStartEnd()[1] - pattern.getStartEnd()[0]) / 15.0f; if (Math.abs(elementWidth - expectedElementWidth) / expectedElementWidth > 0.3f) { throw NotFoundException.getNotFoundInstance(); } int[] oddCounts = this.getOddCounts(); int[] evenCounts = this.getEvenCounts(); float[] oddRoundingErrors = this.getOddRoundingErrors(); float[] evenRoundingErrors = this.getEvenRoundingErrors(); for (int i = 0; i < counters.length; i++) { float value = 1.0f * counters[i] / elementWidth; int count = (int) (value + 0.5f); // Round if (count < 1) { if (value < 0.3f) { throw NotFoundException.getNotFoundInstance(); } count = 1; } else if (count > 8) { if (value > 8.7f) { throw NotFoundException.getNotFoundInstance(); } count = 8; } int offset = i >> 1; if ((i & 0x01) == 0) { oddCounts[offset] = count; oddRoundingErrors[offset] = value - count; } else { evenCounts[offset] = count; evenRoundingErrors[offset] = value - count; } } adjustOddEvenCounts(numModules); int weightRowNumber = 4 * pattern.getValue() + (isOddPattern?0:2) + (leftChar?0:1) - 1; int oddSum = 0; int oddChecksumPortion = 0; for (int i = oddCounts.length - 1; i >= 0; i--) { if(isNotA1left(pattern, isOddPattern, leftChar)){ int weight = WEIGHTS[weightRowNumber][2 * i]; oddChecksumPortion += oddCounts[i] * weight; } oddSum += oddCounts[i]; } int evenChecksumPortion = 0; //int evenSum = 0; for (int i = evenCounts.length - 1; i >= 0; i--) { if(isNotA1left(pattern, isOddPattern, leftChar)){ int weight = WEIGHTS[weightRowNumber][2 * i + 1]; evenChecksumPortion += evenCounts[i] * weight; } //evenSum += evenCounts[i]; } int checksumPortion = oddChecksumPortion + evenChecksumPortion; if ((oddSum & 0x01) != 0 || oddSum > 13 || oddSum < 4) { throw NotFoundException.getNotFoundInstance(); } int group = (13 - oddSum) / 2; int oddWidest = SYMBOL_WIDEST[group]; int evenWidest = 9 - oddWidest; int vOdd = RSSUtils.getRSSvalue(oddCounts, oddWidest, true); int vEven = RSSUtils.getRSSvalue(evenCounts, evenWidest, false); int tEven = EVEN_TOTAL_SUBSET[group]; int gSum = GSUM[group]; int value = vOdd * tEven + vEven + gSum; return new DataCharacter(value, checksumPortion); } private static boolean isNotA1left(FinderPattern pattern, boolean isOddPattern, boolean leftChar) { // A1: pattern.getValue is 0 (A), and it's an oddPattern, and it is a left char return !(pattern.getValue() == 0 && isOddPattern && leftChar); } private void adjustOddEvenCounts(int numModules) throws NotFoundException { int oddSum = count(this.getOddCounts()); int evenSum = count(this.getEvenCounts()); int mismatch = oddSum + evenSum - numModules; boolean oddParityBad = (oddSum & 0x01) == 1; boolean evenParityBad = (evenSum & 0x01) == 0; boolean incrementOdd = false; boolean decrementOdd = false; if (oddSum > 13) { decrementOdd = true; } else if (oddSum < 4) { incrementOdd = true; } boolean incrementEven = false; boolean decrementEven = false; if (evenSum > 13) { decrementEven = true; } else if (evenSum < 4) { incrementEven = true; } if (mismatch == 1) { if (oddParityBad) { if (evenParityBad) { throw NotFoundException.getNotFoundInstance(); } decrementOdd = true; } else { if (!evenParityBad) { throw NotFoundException.getNotFoundInstance(); } decrementEven = true; } } else if (mismatch == -1) { if (oddParityBad) { if (evenParityBad) { throw NotFoundException.getNotFoundInstance(); } incrementOdd = true; } else { if (!evenParityBad) { throw NotFoundException.getNotFoundInstance(); } incrementEven = true; } } else if (mismatch == 0) { if (oddParityBad) { if (!evenParityBad) { throw NotFoundException.getNotFoundInstance(); } // Both bad if (oddSum < evenSum) { incrementOdd = true; decrementEven = true; } else { decrementOdd = true; incrementEven = true; } } else { if (evenParityBad) { throw NotFoundException.getNotFoundInstance(); } // Nothing to do! } } else { throw NotFoundException.getNotFoundInstance(); } if (incrementOdd) { if (decrementOdd) { throw NotFoundException.getNotFoundInstance(); } increment(this.getOddCounts(), this.getOddRoundingErrors()); } if (decrementOdd) { decrement(this.getOddCounts(), this.getOddRoundingErrors()); } if (incrementEven) { if (decrementEven) { throw NotFoundException.getNotFoundInstance(); } increment(this.getEvenCounts(), this.getOddRoundingErrors()); } if (decrementEven) { decrement(this.getEvenCounts(), this.getEvenRoundingErrors()); } } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/oned/rss/expanded/RSSExpandedReader.java
Java
epl
25,246
/* * Copyright (C) 2010 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.oned.rss.expanded; import java.util.ArrayList; import java.util.List; /** * One row of an RSS Expanded Stacked symbol, consisting of 1+ expanded pairs. */ final class ExpandedRow { private final List<ExpandedPair> pairs; private final int rowNumber; /** Did this row of the image have to be reversed (mirrored) to recognize the pairs? */ private final boolean wasReversed; ExpandedRow(List<ExpandedPair> pairs, int rowNumber, boolean wasReversed) { this.pairs = new ArrayList<ExpandedPair>(pairs); this.rowNumber = rowNumber; this.wasReversed = wasReversed; } List<ExpandedPair> getPairs() { return this.pairs; } int getRowNumber() { return this.rowNumber; } boolean isReversed() { return this.wasReversed; } boolean isEquivalent(List<ExpandedPair> otherPairs) { return this.pairs.equals(otherPairs); } @Override public String toString() { return "{ " + pairs + " }"; } /** * Two rows are equal if they contain the same pairs in the same order. */ @Override public boolean equals(Object o) { if (!(o instanceof ExpandedRow)) { return false; } ExpandedRow that = (ExpandedRow) o; return this.pairs.equals(that.getPairs()) && wasReversed == that.wasReversed; } @Override public int hashCode() { return pairs.hashCode() ^ Boolean.valueOf(wasReversed).hashCode(); } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/oned/rss/expanded/ExpandedRow.java
Java
epl
2,031
/* * Copyright (C) 2010 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * These authors would like to acknowledge the Spanish Ministry of Industry, * Tourism and Trade, for the support in the project TSI020301-2008-2 * "PIRAmIDE: Personalizable Interactions with Resources on AmI-enabled * Mobile Dynamic Environments", led by Treelogic * ( http://www.treelogic.com/ ): * * http://www.piramidepse.com/ */ package com.google.zxing.oned.rss.expanded.decoders; /** * @author Pablo Orduña, University of Deusto (pablo.orduna@deusto.es) * @author Eduardo Castillejo, University of Deusto (eduardo.castillejo@deusto.es) */ final class DecodedNumeric extends DecodedObject { private final int firstDigit; private final int secondDigit; static final int FNC1 = 10; DecodedNumeric(int newPosition, int firstDigit, int secondDigit){ super(newPosition); this.firstDigit = firstDigit; this.secondDigit = secondDigit; if (this.firstDigit < 0 || this.firstDigit > 10) { throw new IllegalArgumentException("Invalid firstDigit: " + firstDigit); } if (this.secondDigit < 0 || this.secondDigit > 10) { throw new IllegalArgumentException("Invalid secondDigit: " + secondDigit); } } int getFirstDigit(){ return this.firstDigit; } int getSecondDigit(){ return this.secondDigit; } int getValue(){ return this.firstDigit * 10 + this.secondDigit; } boolean isFirstDigitFNC1(){ return this.firstDigit == FNC1; } boolean isSecondDigitFNC1(){ return this.secondDigit == FNC1; } boolean isAnyFNC1(){ return this.firstDigit == FNC1 || this.secondDigit == FNC1; } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/oned/rss/expanded/decoders/DecodedNumeric.java
Java
epl
2,198
/* * Copyright (C) 2010 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * These authors would like to acknowledge the Spanish Ministry of Industry, * Tourism and Trade, for the support in the project TSI020301-2008-2 * "PIRAmIDE: Personalizable Interactions with Resources on AmI-enabled * Mobile Dynamic Environments", led by Treelogic * ( http://www.treelogic.com/ ): * * http://www.piramidepse.com/ */ package com.google.zxing.oned.rss.expanded.decoders; import com.google.zxing.NotFoundException; /** * @author Pablo Orduña, University of Deusto (pablo.orduna@deusto.es) * @author Eduardo Castillejo, University of Deusto (eduardo.castillejo@deusto.es) */ final class FieldParser { private static final Object VARIABLE_LENGTH = new Object(); private static final Object [][] TWO_DIGIT_DATA_LENGTH = { // "DIGITS", new Integer(LENGTH) // or // "DIGITS", VARIABLE_LENGTH, new Integer(MAX_SIZE) { "00", 18}, { "01", 14}, { "02", 14}, { "10", VARIABLE_LENGTH, 20}, { "11", 6}, { "12", 6}, { "13", 6}, { "15", 6}, { "17", 6}, { "20", 2}, { "21", VARIABLE_LENGTH, 20}, { "22", VARIABLE_LENGTH, 29}, { "30", VARIABLE_LENGTH, 8}, { "37", VARIABLE_LENGTH, 8}, //internal company codes { "90", VARIABLE_LENGTH, 30}, { "91", VARIABLE_LENGTH, 30}, { "92", VARIABLE_LENGTH, 30}, { "93", VARIABLE_LENGTH, 30}, { "94", VARIABLE_LENGTH, 30}, { "95", VARIABLE_LENGTH, 30}, { "96", VARIABLE_LENGTH, 30}, { "97", VARIABLE_LENGTH, 30}, { "98", VARIABLE_LENGTH, 30}, { "99", VARIABLE_LENGTH, 30}, }; private static final Object [][] THREE_DIGIT_DATA_LENGTH = { // Same format as above { "240", VARIABLE_LENGTH, 30}, { "241", VARIABLE_LENGTH, 30}, { "242", VARIABLE_LENGTH, 6}, { "250", VARIABLE_LENGTH, 30}, { "251", VARIABLE_LENGTH, 30}, { "253", VARIABLE_LENGTH, 17}, { "254", VARIABLE_LENGTH, 20}, { "400", VARIABLE_LENGTH, 30}, { "401", VARIABLE_LENGTH, 30}, { "402", 17}, { "403", VARIABLE_LENGTH, 30}, { "410", 13}, { "411", 13}, { "412", 13}, { "413", 13}, { "414", 13}, { "420", VARIABLE_LENGTH, 20}, { "421", VARIABLE_LENGTH, 15}, { "422", 3}, { "423", VARIABLE_LENGTH, 15}, { "424", 3}, { "425", 3}, { "426", 3}, }; private static final Object [][] THREE_DIGIT_PLUS_DIGIT_DATA_LENGTH = { // Same format as above { "310", 6}, { "311", 6}, { "312", 6}, { "313", 6}, { "314", 6}, { "315", 6}, { "316", 6}, { "320", 6}, { "321", 6}, { "322", 6}, { "323", 6}, { "324", 6}, { "325", 6}, { "326", 6}, { "327", 6}, { "328", 6}, { "329", 6}, { "330", 6}, { "331", 6}, { "332", 6}, { "333", 6}, { "334", 6}, { "335", 6}, { "336", 6}, { "340", 6}, { "341", 6}, { "342", 6}, { "343", 6}, { "344", 6}, { "345", 6}, { "346", 6}, { "347", 6}, { "348", 6}, { "349", 6}, { "350", 6}, { "351", 6}, { "352", 6}, { "353", 6}, { "354", 6}, { "355", 6}, { "356", 6}, { "357", 6}, { "360", 6}, { "361", 6}, { "362", 6}, { "363", 6}, { "364", 6}, { "365", 6}, { "366", 6}, { "367", 6}, { "368", 6}, { "369", 6}, { "390", VARIABLE_LENGTH, 15}, { "391", VARIABLE_LENGTH, 18}, { "392", VARIABLE_LENGTH, 15}, { "393", VARIABLE_LENGTH, 18}, { "703", VARIABLE_LENGTH, 30} }; private static final Object [][] FOUR_DIGIT_DATA_LENGTH = { // Same format as above { "7001", 13}, { "7002", VARIABLE_LENGTH, 30}, { "7003", 10}, { "8001", 14}, { "8002", VARIABLE_LENGTH, 20}, { "8003", VARIABLE_LENGTH, 30}, { "8004", VARIABLE_LENGTH, 30}, { "8005", 6}, { "8006", 18}, { "8007", VARIABLE_LENGTH, 30}, { "8008", VARIABLE_LENGTH, 12}, { "8018", 18}, { "8020", VARIABLE_LENGTH, 25}, { "8100", 6}, { "8101", 10}, { "8102", 2}, { "8110", VARIABLE_LENGTH, 70}, { "8200", VARIABLE_LENGTH, 70}, }; private FieldParser() { } static String parseFieldsInGeneralPurpose(String rawInformation) throws NotFoundException{ if(rawInformation.length() == 0) { return null; } // Processing 2-digit AIs if(rawInformation.length() < 2) { throw NotFoundException.getNotFoundInstance(); } String firstTwoDigits = rawInformation.substring(0, 2); for (Object[] dataLength : TWO_DIGIT_DATA_LENGTH) { if (dataLength[0].equals(firstTwoDigits)) { if (dataLength[1] == VARIABLE_LENGTH) { return processVariableAI(2, (Integer) dataLength[2], rawInformation); } return processFixedAI(2, (Integer) dataLength[1], rawInformation); } } if(rawInformation.length() < 3) { throw NotFoundException.getNotFoundInstance(); } String firstThreeDigits = rawInformation.substring(0, 3); for (Object[] dataLength : THREE_DIGIT_DATA_LENGTH) { if (dataLength[0].equals(firstThreeDigits)) { if (dataLength[1] == VARIABLE_LENGTH) { return processVariableAI(3, (Integer) dataLength[2], rawInformation); } return processFixedAI(3, (Integer) dataLength[1], rawInformation); } } for (Object[] dataLength : THREE_DIGIT_PLUS_DIGIT_DATA_LENGTH) { if (dataLength[0].equals(firstThreeDigits)) { if (dataLength[1] == VARIABLE_LENGTH) { return processVariableAI(4, (Integer) dataLength[2], rawInformation); } return processFixedAI(4, (Integer) dataLength[1], rawInformation); } } if(rawInformation.length() < 4) { throw NotFoundException.getNotFoundInstance(); } String firstFourDigits = rawInformation.substring(0, 4); for (Object[] dataLength : FOUR_DIGIT_DATA_LENGTH) { if (dataLength[0].equals(firstFourDigits)) { if (dataLength[1] == VARIABLE_LENGTH) { return processVariableAI(4, (Integer) dataLength[2], rawInformation); } return processFixedAI(4, (Integer) dataLength[1], rawInformation); } } throw NotFoundException.getNotFoundInstance(); } private static String processFixedAI(int aiSize, int fieldSize, String rawInformation) throws NotFoundException{ if (rawInformation.length() < aiSize) { throw NotFoundException.getNotFoundInstance(); } String ai = rawInformation.substring(0, aiSize); if(rawInformation.length() < aiSize + fieldSize) { throw NotFoundException.getNotFoundInstance(); } String field = rawInformation.substring(aiSize, aiSize + fieldSize); String remaining = rawInformation.substring(aiSize + fieldSize); String result = '(' + ai + ')' + field; String parsedAI = parseFieldsInGeneralPurpose(remaining); return parsedAI == null ? result : result + parsedAI; } private static String processVariableAI(int aiSize, int variableFieldSize, String rawInformation) throws NotFoundException { String ai = rawInformation.substring(0, aiSize); int maxSize; if (rawInformation.length() < aiSize + variableFieldSize) { maxSize = rawInformation.length(); } else { maxSize = aiSize + variableFieldSize; } String field = rawInformation.substring(aiSize, maxSize); String remaining = rawInformation.substring(maxSize); String result = '(' + ai + ')' + field; String parsedAI = parseFieldsInGeneralPurpose(remaining); return parsedAI == null ? result : result + parsedAI; } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/oned/rss/expanded/decoders/FieldParser.java
Java
epl
8,123
/* * Copyright (C) 2010 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * These authors would like to acknowledge the Spanish Ministry of Industry, * Tourism and Trade, for the support in the project TSI020301-2008-2 * "PIRAmIDE: Personalizable Interactions with Resources on AmI-enabled * Mobile Dynamic Environments", led by Treelogic * ( http://www.treelogic.com/ ): * * http://www.piramidepse.com/ */ package com.google.zxing.oned.rss.expanded.decoders; import com.google.zxing.common.BitArray; /** * @author Pablo Orduña, University of Deusto (pablo.orduna@deusto.es) * @author Eduardo Castillejo, University of Deusto (eduardo.castillejo@deusto.es) */ abstract class AI01decoder extends AbstractExpandedDecoder { protected static final int GTIN_SIZE = 40; AI01decoder(BitArray information) { super(information); } protected final void encodeCompressedGtin(StringBuilder buf, int currentPos) { buf.append("(01)"); int initialPosition = buf.length(); buf.append('9'); encodeCompressedGtinWithoutAI(buf, currentPos, initialPosition); } protected final void encodeCompressedGtinWithoutAI(StringBuilder buf, int currentPos, int initialBufferPosition) { for(int i = 0; i < 4; ++i){ int currentBlock = this.getGeneralDecoder().extractNumericValueFromBitArray(currentPos + 10 * i, 10); if (currentBlock / 100 == 0) { buf.append('0'); } if (currentBlock / 10 == 0) { buf.append('0'); } buf.append(currentBlock); } appendCheckDigit(buf, initialBufferPosition); } private static void appendCheckDigit(StringBuilder buf, int currentPos){ int checkDigit = 0; for (int i = 0; i < 13; i++) { int digit = buf.charAt(i + currentPos) - '0'; checkDigit += (i & 0x01) == 0 ? 3 * digit : digit; } checkDigit = 10 - (checkDigit % 10); if (checkDigit == 10) { checkDigit = 0; } buf.append(checkDigit); } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/oned/rss/expanded/decoders/AI01decoder.java
Java
epl
2,500
/* * Copyright (C) 2010 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * These authors would like to acknowledge the Spanish Ministry of Industry, * Tourism and Trade, for the support in the project TSI020301-2008-2 * "PIRAmIDE: Personalizable Interactions with Resources on AmI-enabled * Mobile Dynamic Environments", led by Treelogic * ( http://www.treelogic.com/ ): * * http://www.piramidepse.com/ */ package com.google.zxing.oned.rss.expanded.decoders; import com.google.zxing.NotFoundException; import com.google.zxing.common.BitArray; /** * @author Pablo Orduña, University of Deusto (pablo.orduna@deusto.es) * @author Eduardo Castillejo, University of Deusto (eduardo.castillejo@deusto.es) */ final class AI013x0x1xDecoder extends AI01weightDecoder { private static final int HEADER_SIZE = 7 + 1; private static final int WEIGHT_SIZE = 20; private static final int DATE_SIZE = 16; private final String dateCode; private final String firstAIdigits; AI013x0x1xDecoder(BitArray information, String firstAIdigits, String dateCode) { super(information); this.dateCode = dateCode; this.firstAIdigits = firstAIdigits; } @Override public String parseInformation() throws NotFoundException { if (this.getInformation().getSize() != HEADER_SIZE + GTIN_SIZE + WEIGHT_SIZE + DATE_SIZE) { throw NotFoundException.getNotFoundInstance(); } StringBuilder buf = new StringBuilder(); encodeCompressedGtin(buf, HEADER_SIZE); encodeCompressedWeight(buf, HEADER_SIZE + GTIN_SIZE, WEIGHT_SIZE); encodeCompressedDate(buf, HEADER_SIZE + GTIN_SIZE + WEIGHT_SIZE); return buf.toString(); } private void encodeCompressedDate(StringBuilder buf, int currentPos) { int numericDate = this.getGeneralDecoder().extractNumericValueFromBitArray(currentPos, DATE_SIZE); if(numericDate == 38400) { return; } buf.append('('); buf.append(this.dateCode); buf.append(')'); int day = numericDate % 32; numericDate /= 32; int month = numericDate % 12 + 1; numericDate /= 12; int year = numericDate; if (year / 10 == 0) { buf.append('0'); } buf.append(year); if (month / 10 == 0) { buf.append('0'); } buf.append(month); if (day / 10 == 0) { buf.append('0'); } buf.append(day); } @Override protected void addWeightCode(StringBuilder buf, int weight) { int lastAI = weight / 100000; buf.append('('); buf.append(this.firstAIdigits); buf.append(lastAI); buf.append(')'); } @Override protected int checkWeight(int weight) { return weight % 100000; } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/oned/rss/expanded/decoders/AI013x0x1xDecoder.java
Java
epl
3,187
/* * Copyright (C) 2010 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * These authors would like to acknowledge the Spanish Ministry of Industry, * Tourism and Trade, for the support in the project TSI020301-2008-2 * "PIRAmIDE: Personalizable Interactions with Resources on AmI-enabled * Mobile Dynamic Environments", led by Treelogic * ( http://www.treelogic.com/ ): * * http://www.piramidepse.com/ */ package com.google.zxing.oned.rss.expanded.decoders; import com.google.zxing.common.BitArray; /** * @author Pablo Orduña, University of Deusto (pablo.orduna@deusto.es) */ final class AI01320xDecoder extends AI013x0xDecoder { AI01320xDecoder(BitArray information) { super(information); } @Override protected void addWeightCode(StringBuilder buf, int weight) { if (weight < 10000) { buf.append("(3202)"); } else { buf.append("(3203)"); } } @Override protected int checkWeight(int weight) { if(weight < 10000) { return weight; } return weight - 10000; } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/oned/rss/expanded/decoders/AI01320xDecoder.java
Java
epl
1,574
/* * Copyright (C) 2010 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * These authors would like to acknowledge the Spanish Ministry of Industry, * Tourism and Trade, for the support in the project TSI020301-2008-2 * "PIRAmIDE: Personalizable Interactions with Resources on AmI-enabled * Mobile Dynamic Environments", led by Treelogic * ( http://www.treelogic.com/ ): * * http://www.piramidepse.com/ */ package com.google.zxing.oned.rss.expanded.decoders; import com.google.zxing.NotFoundException; import com.google.zxing.common.BitArray; /** * @author Pablo Orduña, University of Deusto (pablo.orduna@deusto.es) */ final class AI01393xDecoder extends AI01decoder { private static final int HEADER_SIZE = 5 + 1 + 2; private static final int LAST_DIGIT_SIZE = 2; private static final int FIRST_THREE_DIGITS_SIZE = 10; AI01393xDecoder(BitArray information) { super(information); } @Override public String parseInformation() throws NotFoundException { if(this.getInformation().getSize() < HEADER_SIZE + GTIN_SIZE) { throw NotFoundException.getNotFoundInstance(); } StringBuilder buf = new StringBuilder(); encodeCompressedGtin(buf, HEADER_SIZE); int lastAIdigit = this.getGeneralDecoder().extractNumericValueFromBitArray(HEADER_SIZE + GTIN_SIZE, LAST_DIGIT_SIZE); buf.append("(393"); buf.append(lastAIdigit); buf.append(')'); int firstThreeDigits = this.getGeneralDecoder().extractNumericValueFromBitArray(HEADER_SIZE + GTIN_SIZE + LAST_DIGIT_SIZE, FIRST_THREE_DIGITS_SIZE); if(firstThreeDigits / 100 == 0) { buf.append('0'); } if(firstThreeDigits / 10 == 0) { buf.append('0'); } buf.append(firstThreeDigits); DecodedInformation generalInformation = this.getGeneralDecoder().decodeGeneralPurposeField(HEADER_SIZE + GTIN_SIZE + LAST_DIGIT_SIZE + FIRST_THREE_DIGITS_SIZE, null); buf.append(generalInformation.getNewString()); return buf.toString(); } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/oned/rss/expanded/decoders/AI01393xDecoder.java
Java
epl
2,540
/* * Copyright (C) 2010 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * These authors would like to acknowledge the Spanish Ministry of Industry, * Tourism and Trade, for the support in the project TSI020301-2008-2 * "PIRAmIDE: Personalizable Interactions with Resources on AmI-enabled * Mobile Dynamic Environments", led by Treelogic * ( http://www.treelogic.com/ ): * * http://www.piramidepse.com/ */ package com.google.zxing.oned.rss.expanded.decoders; import com.google.zxing.NotFoundException; import com.google.zxing.common.BitArray; /** * @author Pablo Orduña, University of Deusto (pablo.orduna@deusto.es) */ final class AI01392xDecoder extends AI01decoder { private static final int HEADER_SIZE = 5 + 1 + 2; private static final int LAST_DIGIT_SIZE = 2; AI01392xDecoder(BitArray information) { super(information); } @Override public String parseInformation() throws NotFoundException { if (this.getInformation().getSize() < HEADER_SIZE + GTIN_SIZE) { throw NotFoundException.getNotFoundInstance(); } StringBuilder buf = new StringBuilder(); encodeCompressedGtin(buf, HEADER_SIZE); int lastAIdigit = this.getGeneralDecoder().extractNumericValueFromBitArray(HEADER_SIZE + GTIN_SIZE, LAST_DIGIT_SIZE); buf.append("(392"); buf.append(lastAIdigit); buf.append(')'); DecodedInformation decodedInformation = this.getGeneralDecoder().decodeGeneralPurposeField(HEADER_SIZE + GTIN_SIZE + LAST_DIGIT_SIZE, null); buf.append(decodedInformation.getNewString()); return buf.toString(); } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/oned/rss/expanded/decoders/AI01392xDecoder.java
Java
epl
2,130
/* * Copyright (C) 2010 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * These authors would like to acknowledge the Spanish Ministry of Industry, * Tourism and Trade, for the support in the project TSI020301-2008-2 * "PIRAmIDE: Personalizable Interactions with Resources on AmI-enabled * Mobile Dynamic Environments", led by Treelogic * ( http://www.treelogic.com/ ): * * http://www.piramidepse.com/ */ package com.google.zxing.oned.rss.expanded.decoders; import com.google.zxing.common.BitArray; /** * @author Pablo Orduña, University of Deusto (pablo.orduna@deusto.es) */ abstract class AI01weightDecoder extends AI01decoder { AI01weightDecoder(BitArray information) { super(information); } protected final void encodeCompressedWeight(StringBuilder buf, int currentPos, int weightSize) { int originalWeightNumeric = this.getGeneralDecoder().extractNumericValueFromBitArray(currentPos, weightSize); addWeightCode(buf, originalWeightNumeric); int weightNumeric = checkWeight(originalWeightNumeric); int currentDivisor = 100000; for(int i = 0; i < 5; ++i){ if (weightNumeric / currentDivisor == 0) { buf.append('0'); } currentDivisor /= 10; } buf.append(weightNumeric); } protected abstract void addWeightCode(StringBuilder buf, int weight); protected abstract int checkWeight(int weight); }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/oned/rss/expanded/decoders/AI01weightDecoder.java
Java
epl
1,920
/* * Copyright (C) 2010 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * These authors would like to acknowledge the Spanish Ministry of Industry, * Tourism and Trade, for the support in the project TSI020301-2008-2 * "PIRAmIDE: Personalizable Interactions with Resources on AmI-enabled * Mobile Dynamic Environments", led by Treelogic * ( http://www.treelogic.com/ ): * * http://www.piramidepse.com/ */ package com.google.zxing.oned.rss.expanded.decoders; /** * @author Pablo Orduña, University of Deusto (pablo.orduna@deusto.es) * @author Eduardo Castillejo, University of Deusto (eduardo.castillejo@deusto.es) */ final class DecodedChar extends DecodedObject { private final char value; static final char FNC1 = '$'; // It's not in Alphanumeric neither in ISO/IEC 646 charset DecodedChar(int newPosition, char value) { super(newPosition); this.value = value; } char getValue(){ return this.value; } boolean isFNC1(){ return this.value == FNC1; } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/oned/rss/expanded/decoders/DecodedChar.java
Java
epl
1,540
/* * Copyright (C) 2010 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * These authors would like to acknowledge the Spanish Ministry of Industry, * Tourism and Trade, for the support in the project TSI020301-2008-2 * "PIRAmIDE: Personalizable Interactions with Resources on AmI-enabled * Mobile Dynamic Environments", led by Treelogic * ( http://www.treelogic.com/ ): * * http://www.piramidepse.com/ */ package com.google.zxing.oned.rss.expanded.decoders; /** * @author Pablo Orduña, University of Deusto (pablo.orduna@deusto.es) */ final class CurrentParsingState { private int position; private State encoding; private enum State { NUMERIC, ALPHA, ISO_IEC_646 } CurrentParsingState() { this.position = 0; this.encoding = State.NUMERIC; } int getPosition() { return position; } void setPosition(int position) { this.position = position; } void incrementPosition(int delta) { position += delta; } boolean isAlpha(){ return this.encoding == State.ALPHA; } boolean isNumeric(){ return this.encoding == State.NUMERIC; } boolean isIsoIec646(){ return this.encoding == State.ISO_IEC_646; } void setNumeric() { this.encoding = State.NUMERIC; } void setAlpha() { this.encoding = State.ALPHA; } void setIsoIec646() { this.encoding = State.ISO_IEC_646; } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/oned/rss/expanded/decoders/CurrentParsingState.java
Java
epl
1,915
/* * Copyright (C) 2010 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * These authors would like to acknowledge the Spanish Ministry of Industry, * Tourism and Trade, for the support in the project TSI020301-2008-2 * "PIRAmIDE: Personalizable Interactions with Resources on AmI-enabled * Mobile Dynamic Environments", led by Treelogic * ( http://www.treelogic.com/ ): * * http://www.piramidepse.com/ */ package com.google.zxing.oned.rss.expanded.decoders; import com.google.zxing.NotFoundException; import com.google.zxing.common.BitArray; /** * @author Pablo Orduña, University of Deusto (pablo.orduna@deusto.es) * @author Eduardo Castillejo, University of Deusto (eduardo.castillejo@deusto.es) */ final class AnyAIDecoder extends AbstractExpandedDecoder { private static final int HEADER_SIZE = 2 + 1 + 2; AnyAIDecoder(BitArray information) { super(information); } @Override public String parseInformation() throws NotFoundException { StringBuilder buf = new StringBuilder(); return this.getGeneralDecoder().decodeAllCodes(buf, HEADER_SIZE); } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/oned/rss/expanded/decoders/AnyAIDecoder.java
Java
epl
1,628
/* * Copyright (C) 2010 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * These authors would like to acknowledge the Spanish Ministry of Industry, * Tourism and Trade, for the support in the project TSI020301-2008-2 * "PIRAmIDE: Personalizable Interactions with Resources on AmI-enabled * Mobile Dynamic Environments", led by Treelogic * ( http://www.treelogic.com/ ): * * http://www.piramidepse.com/ */ package com.google.zxing.oned.rss.expanded.decoders; /** * @author Pablo Orduña, University of Deusto (pablo.orduna@deusto.es) */ abstract class DecodedObject { private final int newPosition; DecodedObject(int newPosition){ this.newPosition = newPosition; } final int getNewPosition() { return this.newPosition; } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/oned/rss/expanded/decoders/DecodedObject.java
Java
epl
1,292
/* * Copyright (C) 2010 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * These authors would like to acknowledge the Spanish Ministry of Industry, * Tourism and Trade, for the support in the project TSI020301-2008-2 * "PIRAmIDE: Personalizable Interactions with Resources on AmI-enabled * Mobile Dynamic Environments", led by Treelogic * ( http://www.treelogic.com/ ): * * http://www.piramidepse.com/ */ package com.google.zxing.oned.rss.expanded.decoders; import com.google.zxing.common.BitArray; /** * @author Pablo Orduña, University of Deusto (pablo.orduna@deusto.es) */ final class AI013103decoder extends AI013x0xDecoder { AI013103decoder(BitArray information) { super(information); } @Override protected void addWeightCode(StringBuilder buf, int weight) { buf.append("(3103)"); } @Override protected int checkWeight(int weight) { return weight; } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/oned/rss/expanded/decoders/AI013103decoder.java
Java
epl
1,438
/* * Copyright (C) 2010 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * These authors would like to acknowledge the Spanish Ministry of Industry, * Tourism and Trade, for the support in the project TSI020301-2008-2 * "PIRAmIDE: Personalizable Interactions with Resources on AmI-enabled * Mobile Dynamic Environments", led by Treelogic * ( http://www.treelogic.com/ ): * * http://www.piramidepse.com/ */ package com.google.zxing.oned.rss.expanded.decoders; import com.google.zxing.NotFoundException; import com.google.zxing.common.BitArray; /** * @author Pablo Orduña, University of Deusto (pablo.orduna@deusto.es) * @author Eduardo Castillejo, University of Deusto (eduardo.castillejo@deusto.es) */ final class GeneralAppIdDecoder { private final BitArray information; private final CurrentParsingState current = new CurrentParsingState(); private final StringBuilder buffer = new StringBuilder(); GeneralAppIdDecoder(BitArray information){ this.information = information; } String decodeAllCodes(StringBuilder buff, int initialPosition) throws NotFoundException { int currentPosition = initialPosition; String remaining = null; do{ DecodedInformation info = this.decodeGeneralPurposeField(currentPosition, remaining); String parsedFields = FieldParser.parseFieldsInGeneralPurpose(info.getNewString()); if (parsedFields != null) { buff.append(parsedFields); } if(info.isRemaining()) { remaining = String.valueOf(info.getRemainingValue()); } else { remaining = null; } if(currentPosition == info.getNewPosition()) {// No step forward! break; } currentPosition = info.getNewPosition(); }while(true); return buff.toString(); } private boolean isStillNumeric(int pos) { // It's numeric if it still has 7 positions // and one of the first 4 bits is "1". if(pos + 7 > this.information.getSize()){ return pos + 4 <= this.information.getSize(); } for (int i = pos; i < pos + 3; ++i) { if (this.information.get(i)) { return true; } } return this.information.get(pos + 3); } private DecodedNumeric decodeNumeric(int pos) { if(pos + 7 > this.information.getSize()){ int numeric = extractNumericValueFromBitArray(pos, 4); if(numeric == 0) { return new DecodedNumeric(this.information.getSize(), DecodedNumeric.FNC1, DecodedNumeric.FNC1); } return new DecodedNumeric(this.information.getSize(), numeric - 1, DecodedNumeric.FNC1); } int numeric = extractNumericValueFromBitArray(pos, 7); int digit1 = (numeric - 8) / 11; int digit2 = (numeric - 8) % 11; return new DecodedNumeric(pos + 7, digit1, digit2); } int extractNumericValueFromBitArray(int pos, int bits){ return extractNumericValueFromBitArray(this.information, pos, bits); } static int extractNumericValueFromBitArray(BitArray information, int pos, int bits) { if(bits > 32) { throw new IllegalArgumentException("extractNumberValueFromBitArray can't handle more than 32 bits"); } int value = 0; for (int i = 0; i < bits; ++i) { if (information.get(pos + i)) { value |= 1 << (bits - i - 1); } } return value; } DecodedInformation decodeGeneralPurposeField(int pos, String remaining) { this.buffer.setLength(0); if(remaining != null) { this.buffer.append(remaining); } this.current.setPosition(pos); DecodedInformation lastDecoded = parseBlocks(); if(lastDecoded != null && lastDecoded.isRemaining()) { return new DecodedInformation(this.current.getPosition(), this.buffer.toString(), lastDecoded.getRemainingValue()); } return new DecodedInformation(this.current.getPosition(), this.buffer.toString()); } private DecodedInformation parseBlocks() { boolean isFinished; BlockParsedResult result; do{ int initialPosition = current.getPosition(); if (current.isAlpha()){ result = parseAlphaBlock(); isFinished = result.isFinished(); }else if (current.isIsoIec646()){ result = parseIsoIec646Block(); isFinished = result.isFinished(); }else{ // it must be numeric result = parseNumericBlock(); isFinished = result.isFinished(); } boolean positionChanged = initialPosition != current.getPosition(); if(!positionChanged && !isFinished) { break; } } while (!isFinished); return result.getDecodedInformation(); } private BlockParsedResult parseNumericBlock() { while (isStillNumeric(current.getPosition())) { DecodedNumeric numeric = decodeNumeric(current.getPosition()); current.setPosition(numeric.getNewPosition()); if(numeric.isFirstDigitFNC1()){ DecodedInformation information; if (numeric.isSecondDigitFNC1()) { information = new DecodedInformation(current.getPosition(), buffer.toString()); } else { information = new DecodedInformation(current.getPosition(), buffer.toString(), numeric.getSecondDigit()); } return new BlockParsedResult(information, true); } buffer.append(numeric.getFirstDigit()); if(numeric.isSecondDigitFNC1()){ DecodedInformation information = new DecodedInformation(current.getPosition(), buffer.toString()); return new BlockParsedResult(information, true); } buffer.append(numeric.getSecondDigit()); } if (isNumericToAlphaNumericLatch(current.getPosition())) { current.setAlpha(); current.incrementPosition(4); } return new BlockParsedResult(false); } private BlockParsedResult parseIsoIec646Block() { while (isStillIsoIec646(current.getPosition())) { DecodedChar iso = decodeIsoIec646(current.getPosition()); current.setPosition(iso.getNewPosition()); if (iso.isFNC1()) { DecodedInformation information = new DecodedInformation(current.getPosition(), buffer.toString()); return new BlockParsedResult(information, true); } buffer.append(iso.getValue()); } if (isAlphaOr646ToNumericLatch(current.getPosition())) { current.incrementPosition(3); current.setNumeric(); } else if (isAlphaTo646ToAlphaLatch(current.getPosition())) { if (current.getPosition() + 5 < this.information.getSize()) { current.incrementPosition(5); } else { current.setPosition(this.information.getSize()); } current.setAlpha(); } return new BlockParsedResult(false); } private BlockParsedResult parseAlphaBlock() { while (isStillAlpha(current.getPosition())) { DecodedChar alpha = decodeAlphanumeric(current.getPosition()); current.setPosition(alpha.getNewPosition()); if(alpha.isFNC1()) { DecodedInformation information = new DecodedInformation(current.getPosition(), buffer.toString()); return new BlockParsedResult(information, true); //end of the char block } buffer.append(alpha.getValue()); } if (isAlphaOr646ToNumericLatch(current.getPosition())) { current.incrementPosition(3); current.setNumeric(); } else if (isAlphaTo646ToAlphaLatch(current.getPosition())) { if (current.getPosition() + 5 < this.information.getSize()) { current.incrementPosition(5); } else { current.setPosition(this.information.getSize()); } current.setIsoIec646(); } return new BlockParsedResult(false); } private boolean isStillIsoIec646(int pos) { if (pos + 5 > this.information.getSize()) { return false; } int fiveBitValue = extractNumericValueFromBitArray(pos, 5); if (fiveBitValue >= 5 && fiveBitValue < 16) { return true; } if (pos + 7 > this.information.getSize()) { return false; } int sevenBitValue = extractNumericValueFromBitArray(pos, 7); if(sevenBitValue >= 64 && sevenBitValue < 116) { return true; } if (pos + 8 > this.information.getSize()) { return false; } int eightBitValue = extractNumericValueFromBitArray(pos, 8); return eightBitValue >= 232 && eightBitValue < 253; } private DecodedChar decodeIsoIec646(int pos) { int fiveBitValue = extractNumericValueFromBitArray(pos, 5); if (fiveBitValue == 15) { return new DecodedChar(pos + 5, DecodedChar.FNC1); } if (fiveBitValue >= 5 && fiveBitValue < 15) { return new DecodedChar(pos + 5, (char) ('0' + fiveBitValue - 5)); } int sevenBitValue = extractNumericValueFromBitArray(pos, 7); if (sevenBitValue >= 64 && sevenBitValue < 90) { return new DecodedChar(pos + 7, (char) (sevenBitValue + 1)); } if (sevenBitValue >= 90 && sevenBitValue < 116) { return new DecodedChar(pos + 7, (char) (sevenBitValue + 7)); } int eightBitValue = extractNumericValueFromBitArray(pos, 8); char c; switch (eightBitValue) { case 232: c = '!'; break; case 233: c = '"'; break; case 234: c = '%'; break; case 235: c = '&'; break; case 236: c = '\''; break; case 237: c = '('; break; case 238: c = ')'; break; case 239: c = '*'; break; case 240: c = '+'; break; case 241: c = ','; break; case 242: c = '-'; break; case 243: c = '.'; break; case 244: c = '/'; break; case 245: c = ':'; break; case 246: c = ';'; break; case 247: c = '<'; break; case 248: c = '='; break; case 249: c = '>'; break; case 250: c = '?'; break; case 251: c = '_'; break; case 252: c = ' '; break; default: throw new IllegalArgumentException("Decoding invalid ISO/IEC 646 value: " + eightBitValue); } return new DecodedChar(pos + 8, c); } private boolean isStillAlpha(int pos) { if(pos + 5 > this.information.getSize()) { return false; } // We now check if it's a valid 5-bit value (0..9 and FNC1) int fiveBitValue = extractNumericValueFromBitArray(pos, 5); if (fiveBitValue >= 5 && fiveBitValue < 16) { return true; } if (pos + 6 > this.information.getSize()) { return false; } int sixBitValue = extractNumericValueFromBitArray(pos, 6); return sixBitValue >= 16 && sixBitValue < 63; // 63 not included } private DecodedChar decodeAlphanumeric(int pos) { int fiveBitValue = extractNumericValueFromBitArray(pos, 5); if (fiveBitValue == 15) { return new DecodedChar(pos + 5, DecodedChar.FNC1); } if (fiveBitValue >= 5 && fiveBitValue < 15) { return new DecodedChar(pos + 5, (char) ('0' + fiveBitValue - 5)); } int sixBitValue = extractNumericValueFromBitArray(pos, 6); if (sixBitValue >= 32 && sixBitValue < 58) { return new DecodedChar(pos + 6, (char) (sixBitValue + 33)); } char c; switch (sixBitValue){ case 58: c = '*'; break; case 59: c = ','; break; case 60: c = '-'; break; case 61: c = '.'; break; case 62: c = '/'; break; default: throw new IllegalStateException("Decoding invalid alphanumeric value: " + sixBitValue); } return new DecodedChar(pos + 6, c); } private boolean isAlphaTo646ToAlphaLatch(int pos) { if (pos + 1 > this.information.getSize()) { return false; } for (int i = 0; i < 5 && i + pos < this.information.getSize(); ++i) { if(i == 2){ if (!this.information.get(pos + 2)) { return false; } } else if (this.information.get(pos + i)) { return false; } } return true; } private boolean isAlphaOr646ToNumericLatch(int pos) { // Next is alphanumeric if there are 3 positions and they are all zeros if (pos + 3 > this.information.getSize()) { return false; } for (int i = pos; i < pos + 3; ++i) { if (this.information.get(i)) { return false; } } return true; } private boolean isNumericToAlphaNumericLatch(int pos) { // Next is alphanumeric if there are 4 positions and they are all zeros, or // if there is a subset of this just before the end of the symbol if (pos + 1 > this.information.getSize()) { return false; } for (int i = 0; i < 4 && i + pos < this.information.getSize(); ++i) { if (this.information.get(pos + i)) { return false; } } return true; } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/oned/rss/expanded/decoders/GeneralAppIdDecoder.java
Java
epl
13,440
/* * Copyright (C) 2010 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * These authors would like to acknowledge the Spanish Ministry of Industry, * Tourism and Trade, for the support in the project TSI020301-2008-2 * "PIRAmIDE: Personalizable Interactions with Resources on AmI-enabled * Mobile Dynamic Environments", led by Treelogic * ( http://www.treelogic.com/ ): * * http://www.piramidepse.com/ */ package com.google.zxing.oned.rss.expanded.decoders; import com.google.zxing.NotFoundException; import com.google.zxing.common.BitArray; /** * @author Pablo Orduña, University of Deusto (pablo.orduna@deusto.es) * @author Eduardo Castillejo, University of Deusto (eduardo.castillejo@deusto.es) */ final class AI01AndOtherAIs extends AI01decoder { private static final int HEADER_SIZE = 1 + 1 + 2; //first bit encodes the linkage flag, //the second one is the encodation method, and the other two are for the variable length AI01AndOtherAIs(BitArray information) { super(information); } @Override public String parseInformation() throws NotFoundException { StringBuilder buff = new StringBuilder(); buff.append("(01)"); int initialGtinPosition = buff.length(); int firstGtinDigit = this.getGeneralDecoder().extractNumericValueFromBitArray(HEADER_SIZE, 4); buff.append(firstGtinDigit); this.encodeCompressedGtinWithoutAI(buff, HEADER_SIZE + 4, initialGtinPosition); return this.getGeneralDecoder().decodeAllCodes(buff, HEADER_SIZE + 44); } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/oned/rss/expanded/decoders/AI01AndOtherAIs.java
Java
epl
2,070
/* * Copyright (C) 2010 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * These authors would like to acknowledge the Spanish Ministry of Industry, * Tourism and Trade, for the support in the project TSI020301-2008-2 * "PIRAmIDE: Personalizable Interactions with Resources on AmI-enabled * Mobile Dynamic Environments", led by Treelogic * ( http://www.treelogic.com/ ): * * http://www.piramidepse.com/ */ package com.google.zxing.oned.rss.expanded.decoders; /** * @author Pablo Orduña, University of Deusto (pablo.orduna@deusto.es) * @author Eduardo Castillejo, University of Deusto (eduardo.castillejo@deusto.es) */ final class BlockParsedResult { private final DecodedInformation decodedInformation; private final boolean finished; BlockParsedResult(boolean finished) { this(null, finished); } BlockParsedResult(DecodedInformation information, boolean finished) { this.finished = finished; this.decodedInformation = information; } DecodedInformation getDecodedInformation() { return this.decodedInformation; } boolean isFinished() { return this.finished; } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/oned/rss/expanded/decoders/BlockParsedResult.java
Java
epl
1,656
/* * Copyright (C) 2010 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * These authors would like to acknowledge the Spanish Ministry of Industry, * Tourism and Trade, for the support in the project TSI020301-2008-2 * "PIRAmIDE: Personalizable Interactions with Resources on AmI-enabled * Mobile Dynamic Environments", led by Treelogic * ( http://www.treelogic.com/ ): * * http://www.piramidepse.com/ */ package com.google.zxing.oned.rss.expanded.decoders; /** * @author Pablo Orduña, University of Deusto (pablo.orduna@deusto.es) * @author Eduardo Castillejo, University of Deusto (eduardo.castillejo@deusto.es) */ final class DecodedInformation extends DecodedObject { private final String newString; private final int remainingValue; private final boolean remaining; DecodedInformation(int newPosition, String newString){ super(newPosition); this.newString = newString; this.remaining = false; this.remainingValue = 0; } DecodedInformation(int newPosition, String newString, int remainingValue){ super(newPosition); this.remaining = true; this.remainingValue = remainingValue; this.newString = newString; } String getNewString(){ return this.newString; } boolean isRemaining(){ return this.remaining; } int getRemainingValue(){ return this.remainingValue; } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/oned/rss/expanded/decoders/DecodedInformation.java
Java
epl
1,890
/* * Copyright (C) 2010 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * These authors would like to acknowledge the Spanish Ministry of Industry, * Tourism and Trade, for the support in the project TSI020301-2008-2 * "PIRAmIDE: Personalizable Interactions with Resources on AmI-enabled * Mobile Dynamic Environments", led by Treelogic * ( http://www.treelogic.com/ ): * * http://www.piramidepse.com/ */ package com.google.zxing.oned.rss.expanded.decoders; import com.google.zxing.NotFoundException; import com.google.zxing.common.BitArray; /** * @author Pablo Orduña, University of Deusto (pablo.orduna@deusto.es) */ abstract class AI013x0xDecoder extends AI01weightDecoder { private static final int HEADER_SIZE = 4 + 1; private static final int WEIGHT_SIZE = 15; AI013x0xDecoder(BitArray information) { super(information); } @Override public String parseInformation() throws NotFoundException { if (this.getInformation().getSize() != HEADER_SIZE + GTIN_SIZE + WEIGHT_SIZE) { throw NotFoundException.getNotFoundInstance(); } StringBuilder buf = new StringBuilder(); encodeCompressedGtin(buf, HEADER_SIZE); encodeCompressedWeight(buf, HEADER_SIZE + GTIN_SIZE, WEIGHT_SIZE); return buf.toString(); } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/oned/rss/expanded/decoders/AI013x0xDecoder.java
Java
epl
1,807
/* * Copyright (C) 2010 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * These authors would like to acknowledge the Spanish Ministry of Industry, * Tourism and Trade, for the support in the project TSI020301-2008-2 * "PIRAmIDE: Personalizable Interactions with Resources on AmI-enabled * Mobile Dynamic Environments", led by Treelogic * ( http://www.treelogic.com/ ): * * http://www.piramidepse.com/ */ package com.google.zxing.oned.rss.expanded.decoders; import com.google.zxing.NotFoundException; import com.google.zxing.common.BitArray; /** * @author Pablo Orduña, University of Deusto (pablo.orduna@deusto.es) * @author Eduardo Castillejo, University of Deusto (eduardo.castillejo@deusto.es) */ public abstract class AbstractExpandedDecoder { private final BitArray information; private final GeneralAppIdDecoder generalDecoder; AbstractExpandedDecoder(BitArray information){ this.information = information; this.generalDecoder = new GeneralAppIdDecoder(information); } protected final BitArray getInformation() { return information; } protected final GeneralAppIdDecoder getGeneralDecoder() { return generalDecoder; } public abstract String parseInformation() throws NotFoundException; public static AbstractExpandedDecoder createDecoder(BitArray information){ if (information.get(1)) { return new AI01AndOtherAIs(information); } if (!information.get(2)) { return new AnyAIDecoder(information); } int fourBitEncodationMethod = GeneralAppIdDecoder.extractNumericValueFromBitArray(information, 1, 4); switch(fourBitEncodationMethod){ case 4: return new AI013103decoder(information); case 5: return new AI01320xDecoder(information); } int fiveBitEncodationMethod = GeneralAppIdDecoder.extractNumericValueFromBitArray(information, 1, 5); switch(fiveBitEncodationMethod){ case 12: return new AI01392xDecoder(information); case 13: return new AI01393xDecoder(information); } int sevenBitEncodationMethod = GeneralAppIdDecoder.extractNumericValueFromBitArray(information, 1, 7); switch(sevenBitEncodationMethod){ case 56: return new AI013x0x1xDecoder(information, "310", "11"); case 57: return new AI013x0x1xDecoder(information, "320", "11"); case 58: return new AI013x0x1xDecoder(information, "310", "13"); case 59: return new AI013x0x1xDecoder(information, "320", "13"); case 60: return new AI013x0x1xDecoder(information, "310", "15"); case 61: return new AI013x0x1xDecoder(information, "320", "15"); case 62: return new AI013x0x1xDecoder(information, "310", "17"); case 63: return new AI013x0x1xDecoder(information, "320", "17"); } throw new IllegalStateException("unknown decoder: " + information); } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/oned/rss/expanded/decoders/AbstractExpandedDecoder.java
Java
epl
3,348
/* * Copyright 2009 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.oned.rss; import com.google.zxing.ResultPoint; public final class FinderPattern { private final int value; private final int[] startEnd; private final ResultPoint[] resultPoints; public FinderPattern(int value, int[] startEnd, int start, int end, int rowNumber) { this.value = value; this.startEnd = startEnd; this.resultPoints = new ResultPoint[] { new ResultPoint((float) start, (float) rowNumber), new ResultPoint((float) end, (float) rowNumber), }; } public int getValue() { return value; } public int[] getStartEnd() { return startEnd; } public ResultPoint[] getResultPoints() { return resultPoints; } @Override public boolean equals(Object o) { if(!(o instanceof FinderPattern)) { return false; } FinderPattern that = (FinderPattern) o; return value == that.value; } @Override public int hashCode() { return value; } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/oned/rss/FinderPattern.java
Java
epl
1,563
/* * Copyright 2009 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.oned.rss; /** Adapted from listings in ISO/IEC 24724 Appendix B and Appendix G. */ public final class RSSUtils { private RSSUtils() {} static int[] getRSSwidths(int val, int n, int elements, int maxWidth, boolean noNarrow) { int[] widths = new int[elements]; int bar; int narrowMask = 0; for (bar = 0; bar < elements - 1; bar++) { narrowMask |= 1 << bar; int elmWidth = 1; int subVal; while (true) { subVal = combins(n - elmWidth - 1, elements - bar - 2); if (noNarrow && (narrowMask == 0) && (n - elmWidth - (elements - bar - 1) >= elements - bar - 1)) { subVal -= combins(n - elmWidth - (elements - bar), elements - bar - 2); } if (elements - bar - 1 > 1) { int lessVal = 0; for (int mxwElement = n - elmWidth - (elements - bar - 2); mxwElement > maxWidth; mxwElement--) { lessVal += combins(n - elmWidth - mxwElement - 1, elements - bar - 3); } subVal -= lessVal * (elements - 1 - bar); } else if (n - elmWidth > maxWidth) { subVal--; } val -= subVal; if (val < 0) { break; } elmWidth++; narrowMask &= ~(1 << bar); } val += subVal; n -= elmWidth; widths[bar] = elmWidth; } widths[bar] = n; return widths; } public static int getRSSvalue(int[] widths, int maxWidth, boolean noNarrow) { int elements = widths.length; int n = 0; for (int width : widths) { n += width; } int val = 0; int narrowMask = 0; for (int bar = 0; bar < elements - 1; bar++) { int elmWidth; for (elmWidth = 1, narrowMask |= 1 << bar; elmWidth < widths[bar]; elmWidth++, narrowMask &= ~(1 << bar)) { int subVal = combins(n - elmWidth - 1, elements - bar - 2); if (noNarrow && (narrowMask == 0) && (n - elmWidth - (elements - bar - 1) >= elements - bar - 1)) { subVal -= combins(n - elmWidth - (elements - bar), elements - bar - 2); } if (elements - bar - 1 > 1) { int lessVal = 0; for (int mxwElement = n - elmWidth - (elements - bar - 2); mxwElement > maxWidth; mxwElement--) { lessVal += combins(n - elmWidth - mxwElement - 1, elements - bar - 3); } subVal -= lessVal * (elements - 1 - bar); } else if (n - elmWidth > maxWidth) { subVal--; } val += subVal; } n -= elmWidth; } return val; } private static int combins(int n, int r) { int maxDenom; int minDenom; if (n - r > r) { minDenom = r; maxDenom = n - r; } else { minDenom = n - r; maxDenom = r; } int val = 1; int j = 1; for (int i = n; i > maxDenom; i--) { val *= i; if (j <= minDenom) { val /= j; j++; } } while (j <= minDenom) { val /= j; j++; } return val; } static int[] elements(int[] eDist, int N, int K) { int[] widths = new int[eDist.length + 2]; int twoK = K << 1; widths[0] = 1; int i; int minEven = 10; int barSum = 1; for (i = 1; i < twoK - 2; i += 2) { widths[i] = eDist[i - 1] - widths[i - 1]; widths[i + 1] = eDist[i] - widths[i]; barSum += widths[i] + widths[i + 1]; if (widths[i] < minEven) { minEven = widths[i]; } } widths[twoK - 1] = N - barSum; if (widths[twoK - 1] < minEven) { minEven = widths[twoK - 1]; } if (minEven > 1) { for (i = 0; i < twoK; i += 2) { widths[i] += minEven - 1; widths[i + 1] -= minEven - 1; } } return widths; } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/oned/rss/RSSUtils.java
Java
epl
4,477
/* * Copyright 2008 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.oned; import com.google.zxing.BarcodeFormat; import com.google.zxing.ChecksumException; import com.google.zxing.DecodeHintType; import com.google.zxing.FormatException; import com.google.zxing.NotFoundException; import com.google.zxing.ReaderException; import com.google.zxing.Result; import com.google.zxing.ResultMetadataType; import com.google.zxing.ResultPoint; import com.google.zxing.ResultPointCallback; import com.google.zxing.common.BitArray; import java.util.Arrays; import java.util.Map; /** * <p>Encapsulates functionality and implementation that is common to UPC and EAN families * of one-dimensional barcodes.</p> * * @author dswitkin@google.com (Daniel Switkin) * @author Sean Owen * @author alasdair@google.com (Alasdair Mackintosh) */ public abstract class UPCEANReader extends OneDReader { // These two values are critical for determining how permissive the decoding will be. // We've arrived at these values through a lot of trial and error. Setting them any higher // lets false positives creep in quickly. private static final int MAX_AVG_VARIANCE = (int) (PATTERN_MATCH_RESULT_SCALE_FACTOR * 0.48f); private static final int MAX_INDIVIDUAL_VARIANCE = (int) (PATTERN_MATCH_RESULT_SCALE_FACTOR * 0.7f); /** * Start/end guard pattern. */ static final int[] START_END_PATTERN = {1, 1, 1,}; /** * Pattern marking the middle of a UPC/EAN pattern, separating the two halves. */ static final int[] MIDDLE_PATTERN = {1, 1, 1, 1, 1}; /** * "Odd", or "L" patterns used to encode UPC/EAN digits. */ static final int[][] L_PATTERNS = { {3, 2, 1, 1}, // 0 {2, 2, 2, 1}, // 1 {2, 1, 2, 2}, // 2 {1, 4, 1, 1}, // 3 {1, 1, 3, 2}, // 4 {1, 2, 3, 1}, // 5 {1, 1, 1, 4}, // 6 {1, 3, 1, 2}, // 7 {1, 2, 1, 3}, // 8 {3, 1, 1, 2} // 9 }; /** * As above but also including the "even", or "G" patterns used to encode UPC/EAN digits. */ static final int[][] L_AND_G_PATTERNS; static { L_AND_G_PATTERNS = new int[20][]; System.arraycopy(L_PATTERNS, 0, L_AND_G_PATTERNS, 0, 10); for (int i = 10; i < 20; i++) { int[] widths = L_PATTERNS[i - 10]; int[] reversedWidths = new int[widths.length]; for (int j = 0; j < widths.length; j++) { reversedWidths[j] = widths[widths.length - j - 1]; } L_AND_G_PATTERNS[i] = reversedWidths; } } private final StringBuilder decodeRowStringBuffer; private final UPCEANExtensionSupport extensionReader; private final EANManufacturerOrgSupport eanManSupport; protected UPCEANReader() { decodeRowStringBuffer = new StringBuilder(20); extensionReader = new UPCEANExtensionSupport(); eanManSupport = new EANManufacturerOrgSupport(); } static int[] findStartGuardPattern(BitArray row) throws NotFoundException { boolean foundStart = false; int[] startRange = null; int nextStart = 0; int[] counters = new int[START_END_PATTERN.length]; while (!foundStart) { Arrays.fill(counters, 0, START_END_PATTERN.length, 0); startRange = findGuardPattern(row, nextStart, false, START_END_PATTERN, counters); int start = startRange[0]; nextStart = startRange[1]; // Make sure there is a quiet zone at least as big as the start pattern before the barcode. // If this check would run off the left edge of the image, do not accept this barcode, // as it is very likely to be a false positive. int quietStart = start - (nextStart - start); if (quietStart >= 0) { foundStart = row.isRange(quietStart, start, false); } } return startRange; } @Override public Result decodeRow(int rowNumber, BitArray row, Map<DecodeHintType,?> hints) throws NotFoundException, ChecksumException, FormatException { return decodeRow(rowNumber, row, findStartGuardPattern(row), hints); } /** * <p>Like {@link #decodeRow(int, BitArray, java.util.Map)}, but * allows caller to inform method about where the UPC/EAN start pattern is * found. This allows this to be computed once and reused across many implementations.</p> */ public Result decodeRow(int rowNumber, BitArray row, int[] startGuardRange, Map<DecodeHintType,?> hints) throws NotFoundException, ChecksumException, FormatException { ResultPointCallback resultPointCallback = hints == null ? null : (ResultPointCallback) hints.get(DecodeHintType.NEED_RESULT_POINT_CALLBACK); if (resultPointCallback != null) { resultPointCallback.foundPossibleResultPoint(new ResultPoint( (startGuardRange[0] + startGuardRange[1]) / 2.0f, rowNumber )); } StringBuilder result = decodeRowStringBuffer; result.setLength(0); int endStart = decodeMiddle(row, startGuardRange, result); if (resultPointCallback != null) { resultPointCallback.foundPossibleResultPoint(new ResultPoint( endStart, rowNumber )); } int[] endRange = decodeEnd(row, endStart); if (resultPointCallback != null) { resultPointCallback.foundPossibleResultPoint(new ResultPoint( (endRange[0] + endRange[1]) / 2.0f, rowNumber )); } // Make sure there is a quiet zone at least as big as the end pattern after the barcode. The // spec might want more whitespace, but in practice this is the maximum we can count on. int end = endRange[1]; int quietEnd = end + (end - endRange[0]); if (quietEnd >= row.getSize() || !row.isRange(end, quietEnd, false)) { throw NotFoundException.getNotFoundInstance(); } String resultString = result.toString(); if (!checkChecksum(resultString)) { throw ChecksumException.getChecksumInstance(); } float left = (float) (startGuardRange[1] + startGuardRange[0]) / 2.0f; float right = (float) (endRange[1] + endRange[0]) / 2.0f; BarcodeFormat format = getBarcodeFormat(); Result decodeResult = new Result(resultString, null, // no natural byte representation for these barcodes new ResultPoint[]{ new ResultPoint(left, (float) rowNumber), new ResultPoint(right, (float) rowNumber)}, format); try { Result extensionResult = extensionReader.decodeRow(rowNumber, row, endRange[1]); decodeResult.putMetadata(ResultMetadataType.UPC_EAN_EXTENSION, extensionResult.getText()); decodeResult.putAllMetadata(extensionResult.getResultMetadata()); decodeResult.addResultPoints(extensionResult.getResultPoints()); } catch (ReaderException re) { // continue } if (format == BarcodeFormat.EAN_13 || format == BarcodeFormat.UPC_A) { String countryID = eanManSupport.lookupCountryIdentifier(resultString); if (countryID != null) { decodeResult.putMetadata(ResultMetadataType.POSSIBLE_COUNTRY, countryID); } } return decodeResult; } /** * @return {@link #checkStandardUPCEANChecksum(CharSequence)} */ boolean checkChecksum(String s) throws ChecksumException, FormatException { return checkStandardUPCEANChecksum(s); } /** * Computes the UPC/EAN checksum on a string of digits, and reports * whether the checksum is correct or not. * * @param s string of digits to check * @return true iff string of digits passes the UPC/EAN checksum algorithm * @throws FormatException if the string does not contain only digits */ static boolean checkStandardUPCEANChecksum(CharSequence s) throws FormatException { int length = s.length(); if (length == 0) { return false; } int sum = 0; for (int i = length - 2; i >= 0; i -= 2) { int digit = (int) s.charAt(i) - (int) '0'; if (digit < 0 || digit > 9) { throw FormatException.getFormatInstance(); } sum += digit; } sum *= 3; for (int i = length - 1; i >= 0; i -= 2) { int digit = (int) s.charAt(i) - (int) '0'; if (digit < 0 || digit > 9) { throw FormatException.getFormatInstance(); } sum += digit; } return sum % 10 == 0; } int[] decodeEnd(BitArray row, int endStart) throws NotFoundException { return findGuardPattern(row, endStart, false, START_END_PATTERN); } static int[] findGuardPattern(BitArray row, int rowOffset, boolean whiteFirst, int[] pattern) throws NotFoundException { return findGuardPattern(row, rowOffset, whiteFirst, pattern, new int[pattern.length]); } /** * @param row row of black/white values to search * @param rowOffset position to start search * @param whiteFirst if true, indicates that the pattern specifies white/black/white/... * pixel counts, otherwise, it is interpreted as black/white/black/... * @param pattern pattern of counts of number of black and white pixels that are being * searched for as a pattern * @param counters array of counters, as long as pattern, to re-use * @return start/end horizontal offset of guard pattern, as an array of two ints * @throws NotFoundException if pattern is not found */ private static int[] findGuardPattern(BitArray row, int rowOffset, boolean whiteFirst, int[] pattern, int[] counters) throws NotFoundException { int patternLength = pattern.length; int width = row.getSize(); boolean isWhite = whiteFirst; rowOffset = whiteFirst ? row.getNextUnset(rowOffset) : row.getNextSet(rowOffset); int counterPosition = 0; int patternStart = rowOffset; for (int x = rowOffset; x < width; x++) { if (row.get(x) ^ isWhite) { counters[counterPosition]++; } else { if (counterPosition == patternLength - 1) { if (patternMatchVariance(counters, pattern, MAX_INDIVIDUAL_VARIANCE) < MAX_AVG_VARIANCE) { return new int[]{patternStart, x}; } patternStart += counters[0] + counters[1]; System.arraycopy(counters, 2, counters, 0, patternLength - 2); counters[patternLength - 2] = 0; counters[patternLength - 1] = 0; counterPosition--; } else { counterPosition++; } counters[counterPosition] = 1; isWhite = !isWhite; } } throw NotFoundException.getNotFoundInstance(); } /** * Attempts to decode a single UPC/EAN-encoded digit. * * @param row row of black/white values to decode * @param counters the counts of runs of observed black/white/black/... values * @param rowOffset horizontal offset to start decoding from * @param patterns the set of patterns to use to decode -- sometimes different encodings * for the digits 0-9 are used, and this indicates the encodings for 0 to 9 that should * be used * @return horizontal offset of first pixel beyond the decoded digit * @throws NotFoundException if digit cannot be decoded */ static int decodeDigit(BitArray row, int[] counters, int rowOffset, int[][] patterns) throws NotFoundException { recordPattern(row, rowOffset, counters); int bestVariance = MAX_AVG_VARIANCE; // worst variance we'll accept int bestMatch = -1; int max = patterns.length; for (int i = 0; i < max; i++) { int[] pattern = patterns[i]; int variance = patternMatchVariance(counters, pattern, MAX_INDIVIDUAL_VARIANCE); if (variance < bestVariance) { bestVariance = variance; bestMatch = i; } } if (bestMatch >= 0) { return bestMatch; } else { throw NotFoundException.getNotFoundInstance(); } } /** * Get the format of this decoder. * * @return The 1D format. */ abstract BarcodeFormat getBarcodeFormat(); /** * Subclasses override this to decode the portion of a barcode between the start * and end guard patterns. * * @param row row of black/white values to search * @param startRange start/end offset of start guard pattern * @param resultString {@link StringBuilder} to append decoded chars to * @return horizontal offset of first pixel after the "middle" that was decoded * @throws NotFoundException if decoding could not complete successfully */ protected abstract int decodeMiddle(BitArray row, int[] startRange, StringBuilder resultString) throws NotFoundException; }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/oned/UPCEANReader.java
Java
epl
13,278
/* * Copyright 2007 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing; import java.util.Map; /** * Implementations of this interface can decode an image of a barcode in some format into * the String it encodes. For example, {@link com.google.zxing.qrcode.QRCodeReader} can * decode a QR code. The decoder may optionally receive hints from the caller which may help * it decode more quickly or accurately. * * See {@link com.google.zxing.MultiFormatReader}, which attempts to determine what barcode * format is present within the image as well, and then decodes it accordingly. * * @author Sean Owen * @author dswitkin@google.com (Daniel Switkin) */ public interface Reader { /** * Locates and decodes a barcode in some format within an image. * * @param image image of barcode to decode * @return String which the barcode encodes * @throws NotFoundException if the barcode cannot be located or decoded for any reason */ Result decode(BinaryBitmap image) throws NotFoundException, ChecksumException, FormatException; /** * Locates and decodes a barcode in some format within an image. This method also accepts * hints, each possibly associated to some data, which may help the implementation decode. * * @param image image of barcode to decode * @param hints passed as a {@link java.util.Map} from {@link com.google.zxing.DecodeHintType} * to arbitrary data. The * meaning of the data depends upon the hint type. The implementation may or may not do * anything with these hints. * @return String which the barcode encodes * @throws NotFoundException if the barcode cannot be located or decoded for any reason */ Result decode(BinaryBitmap image, Map<DecodeHintType,?> hints) throws NotFoundException, ChecksumException, FormatException; /** * Resets any internal state the implementation has after a decode, to prepare it * for reuse. */ void reset(); }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/Reader.java
Java
epl
2,501
/* * Copyright 2008 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.datamatrix.detector; import com.google.zxing.NotFoundException; import com.google.zxing.ResultPoint; import com.google.zxing.common.BitMatrix; import com.google.zxing.common.DetectorResult; import com.google.zxing.common.GridSampler; import com.google.zxing.common.detector.MathUtils; import com.google.zxing.common.detector.WhiteRectangleDetector; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; /** * <p>Encapsulates logic that can detect a Data Matrix Code in an image, even if the Data Matrix Code * is rotated or skewed, or partially obscured.</p> * * @author Sean Owen */ public final class Detector { private final BitMatrix image; private final WhiteRectangleDetector rectangleDetector; public Detector(BitMatrix image) throws NotFoundException { this.image = image; rectangleDetector = new WhiteRectangleDetector(image); } /** * <p>Detects a Data Matrix Code in an image.</p> * * @return {@link DetectorResult} encapsulating results of detecting a Data Matrix Code * @throws NotFoundException if no Data Matrix Code can be found */ public DetectorResult detect() throws NotFoundException { ResultPoint[] cornerPoints = rectangleDetector.detect(); ResultPoint pointA = cornerPoints[0]; ResultPoint pointB = cornerPoints[1]; ResultPoint pointC = cornerPoints[2]; ResultPoint pointD = cornerPoints[3]; // Point A and D are across the diagonal from one another, // as are B and C. Figure out which are the solid black lines // by counting transitions List<ResultPointsAndTransitions> transitions = new ArrayList<ResultPointsAndTransitions>(4); transitions.add(transitionsBetween(pointA, pointB)); transitions.add(transitionsBetween(pointA, pointC)); transitions.add(transitionsBetween(pointB, pointD)); transitions.add(transitionsBetween(pointC, pointD)); Collections.sort(transitions, new ResultPointsAndTransitionsComparator()); // Sort by number of transitions. First two will be the two solid sides; last two // will be the two alternating black/white sides ResultPointsAndTransitions lSideOne = transitions.get(0); ResultPointsAndTransitions lSideTwo = transitions.get(1); // Figure out which point is their intersection by tallying up the number of times we see the // endpoints in the four endpoints. One will show up twice. Map<ResultPoint,Integer> pointCount = new HashMap<ResultPoint,Integer>(); increment(pointCount, lSideOne.getFrom()); increment(pointCount, lSideOne.getTo()); increment(pointCount, lSideTwo.getFrom()); increment(pointCount, lSideTwo.getTo()); ResultPoint maybeTopLeft = null; ResultPoint bottomLeft = null; ResultPoint maybeBottomRight = null; for (Map.Entry<ResultPoint,Integer> entry : pointCount.entrySet()) { ResultPoint point = entry.getKey(); Integer value = entry.getValue(); if (value == 2) { bottomLeft = point; // this is definitely the bottom left, then -- end of two L sides } else { // Otherwise it's either top left or bottom right -- just assign the two arbitrarily now if (maybeTopLeft == null) { maybeTopLeft = point; } else { maybeBottomRight = point; } } } if (maybeTopLeft == null || bottomLeft == null || maybeBottomRight == null) { throw NotFoundException.getNotFoundInstance(); } // Bottom left is correct but top left and bottom right might be switched ResultPoint[] corners = { maybeTopLeft, bottomLeft, maybeBottomRight }; // Use the dot product trick to sort them out ResultPoint.orderBestPatterns(corners); // Now we know which is which: ResultPoint bottomRight = corners[0]; bottomLeft = corners[1]; ResultPoint topLeft = corners[2]; // Which point didn't we find in relation to the "L" sides? that's the top right corner ResultPoint topRight; if (!pointCount.containsKey(pointA)) { topRight = pointA; } else if (!pointCount.containsKey(pointB)) { topRight = pointB; } else if (!pointCount.containsKey(pointC)) { topRight = pointC; } else { topRight = pointD; } // Next determine the dimension by tracing along the top or right side and counting black/white // transitions. Since we start inside a black module, we should see a number of transitions // equal to 1 less than the code dimension. Well, actually 2 less, because we are going to // end on a black module: // The top right point is actually the corner of a module, which is one of the two black modules // adjacent to the white module at the top right. Tracing to that corner from either the top left // or bottom right should work here. int dimensionTop = transitionsBetween(topLeft, topRight).getTransitions(); int dimensionRight = transitionsBetween(bottomRight, topRight).getTransitions(); if ((dimensionTop & 0x01) == 1) { // it can't be odd, so, round... up? dimensionTop++; } dimensionTop += 2; if ((dimensionRight & 0x01) == 1) { // it can't be odd, so, round... up? dimensionRight++; } dimensionRight += 2; BitMatrix bits; ResultPoint correctedTopRight; // Rectanguar symbols are 6x16, 6x28, 10x24, 10x32, 14x32, or 14x44. If one dimension is more // than twice the other, it's certainly rectangular, but to cut a bit more slack we accept it as // rectangular if the bigger side is at least 7/4 times the other: if (4 * dimensionTop >= 7 * dimensionRight || 4 * dimensionRight >= 7 * dimensionTop) { // The matrix is rectangular correctedTopRight = correctTopRightRectangular(bottomLeft, bottomRight, topLeft, topRight, dimensionTop, dimensionRight); if (correctedTopRight == null){ correctedTopRight = topRight; } dimensionTop = transitionsBetween(topLeft, correctedTopRight).getTransitions(); dimensionRight = transitionsBetween(bottomRight, correctedTopRight).getTransitions(); if ((dimensionTop & 0x01) == 1) { // it can't be odd, so, round... up? dimensionTop++; } if ((dimensionRight & 0x01) == 1) { // it can't be odd, so, round... up? dimensionRight++; } bits = sampleGrid(image, topLeft, bottomLeft, bottomRight, correctedTopRight, dimensionTop, dimensionRight); } else { // The matrix is square int dimension = Math.min(dimensionRight, dimensionTop); // correct top right point to match the white module correctedTopRight = correctTopRight(bottomLeft, bottomRight, topLeft, topRight, dimension); if (correctedTopRight == null){ correctedTopRight = topRight; } // Redetermine the dimension using the corrected top right point int dimensionCorrected = Math.max(transitionsBetween(topLeft, correctedTopRight).getTransitions(), transitionsBetween(bottomRight, correctedTopRight).getTransitions()); dimensionCorrected++; if ((dimensionCorrected & 0x01) == 1) { dimensionCorrected++; } bits = sampleGrid(image, topLeft, bottomLeft, bottomRight, correctedTopRight, dimensionCorrected, dimensionCorrected); } return new DetectorResult(bits, new ResultPoint[]{topLeft, bottomLeft, bottomRight, correctedTopRight}); } /** * Calculates the position of the white top right module using the output of the rectangle detector * for a rectangular matrix */ private ResultPoint correctTopRightRectangular(ResultPoint bottomLeft, ResultPoint bottomRight, ResultPoint topLeft, ResultPoint topRight, int dimensionTop, int dimensionRight) { float corr = distance(bottomLeft, bottomRight) / (float)dimensionTop; int norm = distance(topLeft, topRight); float cos = (topRight.getX() - topLeft.getX()) / norm; float sin = (topRight.getY() - topLeft.getY()) / norm; ResultPoint c1 = new ResultPoint(topRight.getX()+corr*cos, topRight.getY()+corr*sin); corr = distance(bottomLeft, topLeft) / (float)dimensionRight; norm = distance(bottomRight, topRight); cos = (topRight.getX() - bottomRight.getX()) / norm; sin = (topRight.getY() - bottomRight.getY()) / norm; ResultPoint c2 = new ResultPoint(topRight.getX()+corr*cos, topRight.getY()+corr*sin); if (!isValid(c1)) { if (isValid(c2)) { return c2; } return null; } if (!isValid(c2)){ return c1; } int l1 = Math.abs(dimensionTop - transitionsBetween(topLeft, c1).getTransitions()) + Math.abs(dimensionRight - transitionsBetween(bottomRight, c1).getTransitions()); int l2 = Math.abs(dimensionTop - transitionsBetween(topLeft, c2).getTransitions()) + Math.abs(dimensionRight - transitionsBetween(bottomRight, c2).getTransitions()); if (l1 <= l2){ return c1; } return c2; } /** * Calculates the position of the white top right module using the output of the rectangle detector * for a square matrix */ private ResultPoint correctTopRight(ResultPoint bottomLeft, ResultPoint bottomRight, ResultPoint topLeft, ResultPoint topRight, int dimension) { float corr = distance(bottomLeft, bottomRight) / (float) dimension; int norm = distance(topLeft, topRight); float cos = (topRight.getX() - topLeft.getX()) / norm; float sin = (topRight.getY() - topLeft.getY()) / norm; ResultPoint c1 = new ResultPoint(topRight.getX() + corr * cos, topRight.getY() + corr * sin); corr = distance(bottomLeft, topLeft) / (float) dimension; norm = distance(bottomRight, topRight); cos = (topRight.getX() - bottomRight.getX()) / norm; sin = (topRight.getY() - bottomRight.getY()) / norm; ResultPoint c2 = new ResultPoint(topRight.getX() + corr * cos, topRight.getY() + corr * sin); if (!isValid(c1)) { if (isValid(c2)) { return c2; } return null; } if (!isValid(c2)) { return c1; } int l1 = Math.abs(transitionsBetween(topLeft, c1).getTransitions() - transitionsBetween(bottomRight, c1).getTransitions()); int l2 = Math.abs(transitionsBetween(topLeft, c2).getTransitions() - transitionsBetween(bottomRight, c2).getTransitions()); return l1 <= l2 ? c1 : c2; } private boolean isValid(ResultPoint p) { return p.getX() >= 0 && p.getX() < image.getWidth() && p.getY() > 0 && p.getY() < image.getHeight(); } private static int distance(ResultPoint a, ResultPoint b) { return MathUtils.round(ResultPoint.distance(a, b)); } /** * Increments the Integer associated with a key by one. */ private static void increment(Map<ResultPoint,Integer> table, ResultPoint key) { Integer value = table.get(key); table.put(key, value == null ? 1 : value + 1); } private static BitMatrix sampleGrid(BitMatrix image, ResultPoint topLeft, ResultPoint bottomLeft, ResultPoint bottomRight, ResultPoint topRight, int dimensionX, int dimensionY) throws NotFoundException { GridSampler sampler = GridSampler.getInstance(); return sampler.sampleGrid(image, dimensionX, dimensionY, 0.5f, 0.5f, dimensionX - 0.5f, 0.5f, dimensionX - 0.5f, dimensionY - 0.5f, 0.5f, dimensionY - 0.5f, topLeft.getX(), topLeft.getY(), topRight.getX(), topRight.getY(), bottomRight.getX(), bottomRight.getY(), bottomLeft.getX(), bottomLeft.getY()); } /** * Counts the number of black/white transitions between two points, using something like Bresenham's algorithm. */ private ResultPointsAndTransitions transitionsBetween(ResultPoint from, ResultPoint to) { // See QR Code Detector, sizeOfBlackWhiteBlackRun() int fromX = (int) from.getX(); int fromY = (int) from.getY(); int toX = (int) to.getX(); int toY = (int) to.getY(); boolean steep = Math.abs(toY - fromY) > Math.abs(toX - fromX); if (steep) { int temp = fromX; fromX = fromY; fromY = temp; temp = toX; toX = toY; toY = temp; } int dx = Math.abs(toX - fromX); int dy = Math.abs(toY - fromY); int error = -dx >> 1; int ystep = fromY < toY ? 1 : -1; int xstep = fromX < toX ? 1 : -1; int transitions = 0; boolean inBlack = image.get(steep ? fromY : fromX, steep ? fromX : fromY); for (int x = fromX, y = fromY; x != toX; x += xstep) { boolean isBlack = image.get(steep ? y : x, steep ? x : y); if (isBlack != inBlack) { transitions++; inBlack = isBlack; } error += dy; if (error > 0) { if (y == toY) { break; } y += ystep; error -= dx; } } return new ResultPointsAndTransitions(from, to, transitions); } /** * Simply encapsulates two points and a number of transitions between them. */ private static final class ResultPointsAndTransitions { private final ResultPoint from; private final ResultPoint to; private final int transitions; private ResultPointsAndTransitions(ResultPoint from, ResultPoint to, int transitions) { this.from = from; this.to = to; this.transitions = transitions; } ResultPoint getFrom() { return from; } ResultPoint getTo() { return to; } public int getTransitions() { return transitions; } @Override public String toString() { return from + "/" + to + '/' + transitions; } } /** * Orders ResultPointsAndTransitions by number of transitions, ascending. */ private static final class ResultPointsAndTransitionsComparator implements Comparator<ResultPointsAndTransitions>, Serializable { @Override public int compare(ResultPointsAndTransitions o1, ResultPointsAndTransitions o2) { return o1.getTransitions() - o2.getTransitions(); } } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/datamatrix/detector/Detector.java
Java
epl
15,989
/* * Copyright 2007 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.datamatrix; import com.google.zxing.BarcodeFormat; import com.google.zxing.BinaryBitmap; import com.google.zxing.ChecksumException; import com.google.zxing.DecodeHintType; import com.google.zxing.FormatException; import com.google.zxing.NotFoundException; import com.google.zxing.Reader; import com.google.zxing.Result; import com.google.zxing.ResultMetadataType; import com.google.zxing.ResultPoint; import com.google.zxing.common.BitMatrix; import com.google.zxing.common.DecoderResult; import com.google.zxing.common.DetectorResult; import com.google.zxing.datamatrix.decoder.Decoder; import com.google.zxing.datamatrix.detector.Detector; import java.util.List; import java.util.Map; /** * This implementation can detect and decode Data Matrix codes in an image. * * @author bbrown@google.com (Brian Brown) */ public final class DataMatrixReader implements Reader { private static final ResultPoint[] NO_POINTS = new ResultPoint[0]; private final Decoder decoder = new Decoder(); /** * Locates and decodes a Data Matrix code in an image. * * @return a String representing the content encoded by the Data Matrix code * @throws NotFoundException if a Data Matrix code cannot be found * @throws FormatException if a Data Matrix code cannot be decoded * @throws ChecksumException if error correction fails */ @Override public Result decode(BinaryBitmap image) throws NotFoundException, ChecksumException, FormatException { return decode(image, null); } @Override public Result decode(BinaryBitmap image, Map<DecodeHintType,?> hints) throws NotFoundException, ChecksumException, FormatException { DecoderResult decoderResult; ResultPoint[] points; if (hints != null && hints.containsKey(DecodeHintType.PURE_BARCODE)) { BitMatrix bits = extractPureBits(image.getBlackMatrix()); decoderResult = decoder.decode(bits); points = NO_POINTS; } else { DetectorResult detectorResult = new Detector(image.getBlackMatrix()).detect(); decoderResult = decoder.decode(detectorResult.getBits()); points = detectorResult.getPoints(); } Result result = new Result(decoderResult.getText(), decoderResult.getRawBytes(), points, BarcodeFormat.DATA_MATRIX); List<byte[]> byteSegments = decoderResult.getByteSegments(); if (byteSegments != null) { result.putMetadata(ResultMetadataType.BYTE_SEGMENTS, byteSegments); } String ecLevel = decoderResult.getECLevel(); if (ecLevel != null) { result.putMetadata(ResultMetadataType.ERROR_CORRECTION_LEVEL, ecLevel); } return result; } @Override public void reset() { // do nothing } /** * This method detects a code in a "pure" image -- that is, pure monochrome image * which contains only an unrotated, unskewed, image of a code, with some white border * around it. This is a specialized method that works exceptionally fast in this special * case. * * @see com.google.zxing.qrcode.QRCodeReader#extractPureBits(BitMatrix) */ private static BitMatrix extractPureBits(BitMatrix image) throws NotFoundException { int[] leftTopBlack = image.getTopLeftOnBit(); int[] rightBottomBlack = image.getBottomRightOnBit(); if (leftTopBlack == null || rightBottomBlack == null) { throw NotFoundException.getNotFoundInstance(); } int moduleSize = moduleSize(leftTopBlack, image); int top = leftTopBlack[1]; int bottom = rightBottomBlack[1]; int left = leftTopBlack[0]; int right = rightBottomBlack[0]; int matrixWidth = (right - left + 1) / moduleSize; int matrixHeight = (bottom - top + 1) / moduleSize; if (matrixWidth <= 0 || matrixHeight <= 0) { throw NotFoundException.getNotFoundInstance(); } // Push in the "border" by half the module width so that we start // sampling in the middle of the module. Just in case the image is a // little off, this will help recover. int nudge = moduleSize >> 1; top += nudge; left += nudge; // Now just read off the bits BitMatrix bits = new BitMatrix(matrixWidth, matrixHeight); for (int y = 0; y < matrixHeight; y++) { int iOffset = top + y * moduleSize; for (int x = 0; x < matrixWidth; x++) { if (image.get(left + x * moduleSize, iOffset)) { bits.set(x, y); } } } return bits; } private static int moduleSize(int[] leftTopBlack, BitMatrix image) throws NotFoundException { int width = image.getWidth(); int x = leftTopBlack[0]; int y = leftTopBlack[1]; while (x < width && image.get(x, y)) { x++; } if (x == width) { throw NotFoundException.getNotFoundInstance(); } int moduleSize = x - leftTopBlack[0]; if (moduleSize == 0) { throw NotFoundException.getNotFoundInstance(); } return moduleSize; } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/datamatrix/DataMatrixReader.java
Java
epl
5,504
/* * Copyright 2007 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.datamatrix.decoder; import com.google.zxing.FormatException; /** * The Version object encapsulates attributes about a particular * size Data Matrix Code. * * @author bbrown@google.com (Brian Brown) */ public final class Version { private static final Version[] VERSIONS = buildVersions(); private final int versionNumber; private final int symbolSizeRows; private final int symbolSizeColumns; private final int dataRegionSizeRows; private final int dataRegionSizeColumns; private final ECBlocks ecBlocks; private final int totalCodewords; private Version(int versionNumber, int symbolSizeRows, int symbolSizeColumns, int dataRegionSizeRows, int dataRegionSizeColumns, ECBlocks ecBlocks) { this.versionNumber = versionNumber; this.symbolSizeRows = symbolSizeRows; this.symbolSizeColumns = symbolSizeColumns; this.dataRegionSizeRows = dataRegionSizeRows; this.dataRegionSizeColumns = dataRegionSizeColumns; this.ecBlocks = ecBlocks; // Calculate the total number of codewords int total = 0; int ecCodewords = ecBlocks.getECCodewords(); ECB[] ecbArray = ecBlocks.getECBlocks(); for (ECB ecBlock : ecbArray) { total += ecBlock.getCount() * (ecBlock.getDataCodewords() + ecCodewords); } this.totalCodewords = total; } public int getVersionNumber() { return versionNumber; } public int getSymbolSizeRows() { return symbolSizeRows; } public int getSymbolSizeColumns() { return symbolSizeColumns; } public int getDataRegionSizeRows() { return dataRegionSizeRows; } public int getDataRegionSizeColumns() { return dataRegionSizeColumns; } public int getTotalCodewords() { return totalCodewords; } ECBlocks getECBlocks() { return ecBlocks; } /** * <p>Deduces version information from Data Matrix dimensions.</p> * * @param numRows Number of rows in modules * @param numColumns Number of columns in modules * @return Version for a Data Matrix Code of those dimensions * @throws FormatException if dimensions do correspond to a valid Data Matrix size */ public static Version getVersionForDimensions(int numRows, int numColumns) throws FormatException { if ((numRows & 0x01) != 0 || (numColumns & 0x01) != 0) { throw FormatException.getFormatInstance(); } for (Version version : VERSIONS) { if (version.symbolSizeRows == numRows && version.symbolSizeColumns == numColumns) { return version; } } throw FormatException.getFormatInstance(); } /** * <p>Encapsulates a set of error-correction blocks in one symbol version. Most versions will * use blocks of differing sizes within one version, so, this encapsulates the parameters for * each set of blocks. It also holds the number of error-correction codewords per block since it * will be the same across all blocks within one version.</p> */ static final class ECBlocks { private final int ecCodewords; private final ECB[] ecBlocks; private ECBlocks(int ecCodewords, ECB ecBlocks) { this.ecCodewords = ecCodewords; this.ecBlocks = new ECB[] { ecBlocks }; } private ECBlocks(int ecCodewords, ECB ecBlocks1, ECB ecBlocks2) { this.ecCodewords = ecCodewords; this.ecBlocks = new ECB[] { ecBlocks1, ecBlocks2 }; } int getECCodewords() { return ecCodewords; } ECB[] getECBlocks() { return ecBlocks; } } /** * <p>Encapsualtes the parameters for one error-correction block in one symbol version. * This includes the number of data codewords, and the number of times a block with these * parameters is used consecutively in the Data Matrix code version's format.</p> */ static final class ECB { private final int count; private final int dataCodewords; private ECB(int count, int dataCodewords) { this.count = count; this.dataCodewords = dataCodewords; } int getCount() { return count; } int getDataCodewords() { return dataCodewords; } } @Override public String toString() { return String.valueOf(versionNumber); } /** * See ISO 16022:2006 5.5.1 Table 7 */ private static Version[] buildVersions() { return new Version[]{ new Version(1, 10, 10, 8, 8, new ECBlocks(5, new ECB(1, 3))), new Version(2, 12, 12, 10, 10, new ECBlocks(7, new ECB(1, 5))), new Version(3, 14, 14, 12, 12, new ECBlocks(10, new ECB(1, 8))), new Version(4, 16, 16, 14, 14, new ECBlocks(12, new ECB(1, 12))), new Version(5, 18, 18, 16, 16, new ECBlocks(14, new ECB(1, 18))), new Version(6, 20, 20, 18, 18, new ECBlocks(18, new ECB(1, 22))), new Version(7, 22, 22, 20, 20, new ECBlocks(20, new ECB(1, 30))), new Version(8, 24, 24, 22, 22, new ECBlocks(24, new ECB(1, 36))), new Version(9, 26, 26, 24, 24, new ECBlocks(28, new ECB(1, 44))), new Version(10, 32, 32, 14, 14, new ECBlocks(36, new ECB(1, 62))), new Version(11, 36, 36, 16, 16, new ECBlocks(42, new ECB(1, 86))), new Version(12, 40, 40, 18, 18, new ECBlocks(48, new ECB(1, 114))), new Version(13, 44, 44, 20, 20, new ECBlocks(56, new ECB(1, 144))), new Version(14, 48, 48, 22, 22, new ECBlocks(68, new ECB(1, 174))), new Version(15, 52, 52, 24, 24, new ECBlocks(42, new ECB(2, 102))), new Version(16, 64, 64, 14, 14, new ECBlocks(56, new ECB(2, 140))), new Version(17, 72, 72, 16, 16, new ECBlocks(36, new ECB(4, 92))), new Version(18, 80, 80, 18, 18, new ECBlocks(48, new ECB(4, 114))), new Version(19, 88, 88, 20, 20, new ECBlocks(56, new ECB(4, 144))), new Version(20, 96, 96, 22, 22, new ECBlocks(68, new ECB(4, 174))), new Version(21, 104, 104, 24, 24, new ECBlocks(56, new ECB(6, 136))), new Version(22, 120, 120, 18, 18, new ECBlocks(68, new ECB(6, 175))), new Version(23, 132, 132, 20, 20, new ECBlocks(62, new ECB(8, 163))), new Version(24, 144, 144, 22, 22, new ECBlocks(62, new ECB(8, 156), new ECB(2, 155))), new Version(25, 8, 18, 6, 16, new ECBlocks(7, new ECB(1, 5))), new Version(26, 8, 32, 6, 14, new ECBlocks(11, new ECB(1, 10))), new Version(27, 12, 26, 10, 24, new ECBlocks(14, new ECB(1, 16))), new Version(28, 12, 36, 10, 16, new ECBlocks(18, new ECB(1, 22))), new Version(29, 16, 36, 14, 16, new ECBlocks(24, new ECB(1, 32))), new Version(30, 16, 48, 14, 22, new ECBlocks(28, new ECB(1, 49))) }; } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/datamatrix/decoder/Version.java
Java
epl
7,890
/* * Copyright 2008 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.datamatrix.decoder; /** * <p>Encapsulates a block of data within a Data Matrix Code. Data Matrix Codes may split their data into * multiple blocks, each of which is a unit of data and error-correction codewords. Each * is represented by an instance of this class.</p> * * @author bbrown@google.com (Brian Brown) */ final class DataBlock { private final int numDataCodewords; private final byte[] codewords; private DataBlock(int numDataCodewords, byte[] codewords) { this.numDataCodewords = numDataCodewords; this.codewords = codewords; } /** * <p>When Data Matrix Codes use multiple data blocks, they actually interleave the bytes of each of them. * That is, the first byte of data block 1 to n is written, then the second bytes, and so on. This * method will separate the data into original blocks.</p> * * @param rawCodewords bytes as read directly from the Data Matrix Code * @param version version of the Data Matrix Code * @return DataBlocks containing original bytes, "de-interleaved" from representation in the * Data Matrix Code */ static DataBlock[] getDataBlocks(byte[] rawCodewords, Version version) { // Figure out the number and size of data blocks used by this version Version.ECBlocks ecBlocks = version.getECBlocks(); // First count the total number of data blocks int totalBlocks = 0; Version.ECB[] ecBlockArray = ecBlocks.getECBlocks(); for (Version.ECB ecBlock : ecBlockArray) { totalBlocks += ecBlock.getCount(); } // Now establish DataBlocks of the appropriate size and number of data codewords DataBlock[] result = new DataBlock[totalBlocks]; int numResultBlocks = 0; for (Version.ECB ecBlock : ecBlockArray) { for (int i = 0; i < ecBlock.getCount(); i++) { int numDataCodewords = ecBlock.getDataCodewords(); int numBlockCodewords = ecBlocks.getECCodewords() + numDataCodewords; result[numResultBlocks++] = new DataBlock(numDataCodewords, new byte[numBlockCodewords]); } } // All blocks have the same amount of data, except that the last n // (where n may be 0) have 1 less byte. Figure out where these start. // TODO(bbrown): There is only one case where there is a difference for Data Matrix for size 144 int longerBlocksTotalCodewords = result[0].codewords.length; //int shorterBlocksTotalCodewords = longerBlocksTotalCodewords - 1; int longerBlocksNumDataCodewords = longerBlocksTotalCodewords - ecBlocks.getECCodewords(); int shorterBlocksNumDataCodewords = longerBlocksNumDataCodewords - 1; // The last elements of result may be 1 element shorter for 144 matrix // first fill out as many elements as all of them have minus 1 int rawCodewordsOffset = 0; for (int i = 0; i < shorterBlocksNumDataCodewords; i++) { for (int j = 0; j < numResultBlocks; j++) { result[j].codewords[i] = rawCodewords[rawCodewordsOffset++]; } } // Fill out the last data block in the longer ones boolean specialVersion = version.getVersionNumber() == 24; int numLongerBlocks = specialVersion ? 8 : numResultBlocks; for (int j = 0; j < numLongerBlocks; j++) { result[j].codewords[longerBlocksNumDataCodewords - 1] = rawCodewords[rawCodewordsOffset++]; } // Now add in error correction blocks int max = result[0].codewords.length; for (int i = longerBlocksNumDataCodewords; i < max; i++) { for (int j = 0; j < numResultBlocks; j++) { int iOffset = specialVersion && j > 7 ? i - 1 : i; result[j].codewords[iOffset] = rawCodewords[rawCodewordsOffset++]; } } if (rawCodewordsOffset != rawCodewords.length) { throw new IllegalArgumentException(); } return result; } int getNumDataCodewords() { return numDataCodewords; } byte[] getCodewords() { return codewords; } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/datamatrix/decoder/DataBlock.java
Java
epl
4,690
/* * Copyright 2007 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.datamatrix.decoder; import com.google.zxing.FormatException; import com.google.zxing.common.BitMatrix; /** * @author bbrown@google.com (Brian Brown) */ final class BitMatrixParser { private final BitMatrix mappingBitMatrix; private final BitMatrix readMappingMatrix; private final Version version; /** * @param bitMatrix {@link BitMatrix} to parse * @throws FormatException if dimension is < 8 or > 144 or not 0 mod 2 */ BitMatrixParser(BitMatrix bitMatrix) throws FormatException { int dimension = bitMatrix.getHeight(); if (dimension < 8 || dimension > 144 || (dimension & 0x01) != 0) { throw FormatException.getFormatInstance(); } version = readVersion(bitMatrix); this.mappingBitMatrix = extractDataRegion(bitMatrix); this.readMappingMatrix = new BitMatrix(this.mappingBitMatrix.getWidth(), this.mappingBitMatrix.getHeight()); } Version getVersion() { return version; } /** * <p>Creates the version object based on the dimension of the original bit matrix from * the datamatrix code.</p> * * <p>See ISO 16022:2006 Table 7 - ECC 200 symbol attributes</p> * * @param bitMatrix Original {@link BitMatrix} including alignment patterns * @return {@link Version} encapsulating the Data Matrix Code's "version" * @throws FormatException if the dimensions of the mapping matrix are not valid * Data Matrix dimensions. */ private static Version readVersion(BitMatrix bitMatrix) throws FormatException { int numRows = bitMatrix.getHeight(); int numColumns = bitMatrix.getWidth(); return Version.getVersionForDimensions(numRows, numColumns); } /** * <p>Reads the bits in the {@link BitMatrix} representing the mapping matrix (No alignment patterns) * in the correct order in order to reconstitute the codewords bytes contained within the * Data Matrix Code.</p> * * @return bytes encoded within the Data Matrix Code * @throws FormatException if the exact number of bytes expected is not read */ byte[] readCodewords() throws FormatException { byte[] result = new byte[version.getTotalCodewords()]; int resultOffset = 0; int row = 4; int column = 0; int numRows = mappingBitMatrix.getHeight(); int numColumns = mappingBitMatrix.getWidth(); boolean corner1Read = false; boolean corner2Read = false; boolean corner3Read = false; boolean corner4Read = false; // Read all of the codewords do { // Check the four corner cases if ((row == numRows) && (column == 0) && !corner1Read) { result[resultOffset++] = (byte) readCorner1(numRows, numColumns); row -= 2; column +=2; corner1Read = true; } else if ((row == numRows-2) && (column == 0) && ((numColumns & 0x03) != 0) && !corner2Read) { result[resultOffset++] = (byte) readCorner2(numRows, numColumns); row -= 2; column +=2; corner2Read = true; } else if ((row == numRows+4) && (column == 2) && ((numColumns & 0x07) == 0) && !corner3Read) { result[resultOffset++] = (byte) readCorner3(numRows, numColumns); row -= 2; column +=2; corner3Read = true; } else if ((row == numRows-2) && (column == 0) && ((numColumns & 0x07) == 4) && !corner4Read) { result[resultOffset++] = (byte) readCorner4(numRows, numColumns); row -= 2; column +=2; corner4Read = true; } else { // Sweep upward diagonally to the right do { if ((row < numRows) && (column >= 0) && !readMappingMatrix.get(column, row)) { result[resultOffset++] = (byte) readUtah(row, column, numRows, numColumns); } row -= 2; column +=2; } while ((row >= 0) && (column < numColumns)); row += 1; column +=3; // Sweep downward diagonally to the left do { if ((row >= 0) && (column < numColumns) && !readMappingMatrix.get(column, row)) { result[resultOffset++] = (byte) readUtah(row, column, numRows, numColumns); } row += 2; column -=2; } while ((row < numRows) && (column >= 0)); row += 3; column +=1; } } while ((row < numRows) || (column < numColumns)); if (resultOffset != version.getTotalCodewords()) { throw FormatException.getFormatInstance(); } return result; } /** * <p>Reads a bit of the mapping matrix accounting for boundary wrapping.</p> * * @param row Row to read in the mapping matrix * @param column Column to read in the mapping matrix * @param numRows Number of rows in the mapping matrix * @param numColumns Number of columns in the mapping matrix * @return value of the given bit in the mapping matrix */ boolean readModule(int row, int column, int numRows, int numColumns) { // Adjust the row and column indices based on boundary wrapping if (row < 0) { row += numRows; column += 4 - ((numRows + 4) & 0x07); } if (column < 0) { column += numColumns; row += 4 - ((numColumns + 4) & 0x07); } readMappingMatrix.set(column, row); return mappingBitMatrix.get(column, row); } /** * <p>Reads the 8 bits of the standard Utah-shaped pattern.</p> * * <p>See ISO 16022:2006, 5.8.1 Figure 6</p> * * @param row Current row in the mapping matrix, anchored at the 8th bit (LSB) of the pattern * @param column Current column in the mapping matrix, anchored at the 8th bit (LSB) of the pattern * @param numRows Number of rows in the mapping matrix * @param numColumns Number of columns in the mapping matrix * @return byte from the utah shape */ int readUtah(int row, int column, int numRows, int numColumns) { int currentByte = 0; if (readModule(row - 2, column - 2, numRows, numColumns)) { currentByte |= 1; } currentByte <<= 1; if (readModule(row - 2, column - 1, numRows, numColumns)) { currentByte |= 1; } currentByte <<= 1; if (readModule(row - 1, column - 2, numRows, numColumns)) { currentByte |= 1; } currentByte <<= 1; if (readModule(row - 1, column - 1, numRows, numColumns)) { currentByte |= 1; } currentByte <<= 1; if (readModule(row - 1, column, numRows, numColumns)) { currentByte |= 1; } currentByte <<= 1; if (readModule(row, column - 2, numRows, numColumns)) { currentByte |= 1; } currentByte <<= 1; if (readModule(row, column - 1, numRows, numColumns)) { currentByte |= 1; } currentByte <<= 1; if (readModule(row, column, numRows, numColumns)) { currentByte |= 1; } return currentByte; } /** * <p>Reads the 8 bits of the special corner condition 1.</p> * * <p>See ISO 16022:2006, Figure F.3</p> * * @param numRows Number of rows in the mapping matrix * @param numColumns Number of columns in the mapping matrix * @return byte from the Corner condition 1 */ int readCorner1(int numRows, int numColumns) { int currentByte = 0; if (readModule(numRows - 1, 0, numRows, numColumns)) { currentByte |= 1; } currentByte <<= 1; if (readModule(numRows - 1, 1, numRows, numColumns)) { currentByte |= 1; } currentByte <<= 1; if (readModule(numRows - 1, 2, numRows, numColumns)) { currentByte |= 1; } currentByte <<= 1; if (readModule(0, numColumns - 2, numRows, numColumns)) { currentByte |= 1; } currentByte <<= 1; if (readModule(0, numColumns - 1, numRows, numColumns)) { currentByte |= 1; } currentByte <<= 1; if (readModule(1, numColumns - 1, numRows, numColumns)) { currentByte |= 1; } currentByte <<= 1; if (readModule(2, numColumns - 1, numRows, numColumns)) { currentByte |= 1; } currentByte <<= 1; if (readModule(3, numColumns - 1, numRows, numColumns)) { currentByte |= 1; } return currentByte; } /** * <p>Reads the 8 bits of the special corner condition 2.</p> * * <p>See ISO 16022:2006, Figure F.4</p> * * @param numRows Number of rows in the mapping matrix * @param numColumns Number of columns in the mapping matrix * @return byte from the Corner condition 2 */ int readCorner2(int numRows, int numColumns) { int currentByte = 0; if (readModule(numRows - 3, 0, numRows, numColumns)) { currentByte |= 1; } currentByte <<= 1; if (readModule(numRows - 2, 0, numRows, numColumns)) { currentByte |= 1; } currentByte <<= 1; if (readModule(numRows - 1, 0, numRows, numColumns)) { currentByte |= 1; } currentByte <<= 1; if (readModule(0, numColumns - 4, numRows, numColumns)) { currentByte |= 1; } currentByte <<= 1; if (readModule(0, numColumns - 3, numRows, numColumns)) { currentByte |= 1; } currentByte <<= 1; if (readModule(0, numColumns - 2, numRows, numColumns)) { currentByte |= 1; } currentByte <<= 1; if (readModule(0, numColumns - 1, numRows, numColumns)) { currentByte |= 1; } currentByte <<= 1; if (readModule(1, numColumns - 1, numRows, numColumns)) { currentByte |= 1; } return currentByte; } /** * <p>Reads the 8 bits of the special corner condition 3.</p> * * <p>See ISO 16022:2006, Figure F.5</p> * * @param numRows Number of rows in the mapping matrix * @param numColumns Number of columns in the mapping matrix * @return byte from the Corner condition 3 */ int readCorner3(int numRows, int numColumns) { int currentByte = 0; if (readModule(numRows - 1, 0, numRows, numColumns)) { currentByte |= 1; } currentByte <<= 1; if (readModule(numRows - 1, numColumns - 1, numRows, numColumns)) { currentByte |= 1; } currentByte <<= 1; if (readModule(0, numColumns - 3, numRows, numColumns)) { currentByte |= 1; } currentByte <<= 1; if (readModule(0, numColumns - 2, numRows, numColumns)) { currentByte |= 1; } currentByte <<= 1; if (readModule(0, numColumns - 1, numRows, numColumns)) { currentByte |= 1; } currentByte <<= 1; if (readModule(1, numColumns - 3, numRows, numColumns)) { currentByte |= 1; } currentByte <<= 1; if (readModule(1, numColumns - 2, numRows, numColumns)) { currentByte |= 1; } currentByte <<= 1; if (readModule(1, numColumns - 1, numRows, numColumns)) { currentByte |= 1; } return currentByte; } /** * <p>Reads the 8 bits of the special corner condition 4.</p> * * <p>See ISO 16022:2006, Figure F.6</p> * * @param numRows Number of rows in the mapping matrix * @param numColumns Number of columns in the mapping matrix * @return byte from the Corner condition 4 */ int readCorner4(int numRows, int numColumns) { int currentByte = 0; if (readModule(numRows - 3, 0, numRows, numColumns)) { currentByte |= 1; } currentByte <<= 1; if (readModule(numRows - 2, 0, numRows, numColumns)) { currentByte |= 1; } currentByte <<= 1; if (readModule(numRows - 1, 0, numRows, numColumns)) { currentByte |= 1; } currentByte <<= 1; if (readModule(0, numColumns - 2, numRows, numColumns)) { currentByte |= 1; } currentByte <<= 1; if (readModule(0, numColumns - 1, numRows, numColumns)) { currentByte |= 1; } currentByte <<= 1; if (readModule(1, numColumns - 1, numRows, numColumns)) { currentByte |= 1; } currentByte <<= 1; if (readModule(2, numColumns - 1, numRows, numColumns)) { currentByte |= 1; } currentByte <<= 1; if (readModule(3, numColumns - 1, numRows, numColumns)) { currentByte |= 1; } return currentByte; } /** * <p>Extracts the data region from a {@link BitMatrix} that contains * alignment patterns.</p> * * @param bitMatrix Original {@link BitMatrix} with alignment patterns * @return BitMatrix that has the alignment patterns removed */ BitMatrix extractDataRegion(BitMatrix bitMatrix) { int symbolSizeRows = version.getSymbolSizeRows(); int symbolSizeColumns = version.getSymbolSizeColumns(); if (bitMatrix.getHeight() != symbolSizeRows) { throw new IllegalArgumentException("Dimension of bitMarix must match the version size"); } int dataRegionSizeRows = version.getDataRegionSizeRows(); int dataRegionSizeColumns = version.getDataRegionSizeColumns(); int numDataRegionsRow = symbolSizeRows / dataRegionSizeRows; int numDataRegionsColumn = symbolSizeColumns / dataRegionSizeColumns; int sizeDataRegionRow = numDataRegionsRow * dataRegionSizeRows; int sizeDataRegionColumn = numDataRegionsColumn * dataRegionSizeColumns; BitMatrix bitMatrixWithoutAlignment = new BitMatrix(sizeDataRegionColumn, sizeDataRegionRow); for (int dataRegionRow = 0; dataRegionRow < numDataRegionsRow; ++dataRegionRow) { int dataRegionRowOffset = dataRegionRow * dataRegionSizeRows; for (int dataRegionColumn = 0; dataRegionColumn < numDataRegionsColumn; ++dataRegionColumn) { int dataRegionColumnOffset = dataRegionColumn * dataRegionSizeColumns; for (int i = 0; i < dataRegionSizeRows; ++i) { int readRowOffset = dataRegionRow * (dataRegionSizeRows + 2) + 1 + i; int writeRowOffset = dataRegionRowOffset + i; for (int j = 0; j < dataRegionSizeColumns; ++j) { int readColumnOffset = dataRegionColumn * (dataRegionSizeColumns + 2) + 1 + j; if (bitMatrix.get(readColumnOffset, readRowOffset)) { int writeColumnOffset = dataRegionColumnOffset + j; bitMatrixWithoutAlignment.set(writeColumnOffset, writeRowOffset); } } } } } return bitMatrixWithoutAlignment; } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/datamatrix/decoder/BitMatrixParser.java
Java
epl
15,105
/* * Copyright 2008 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.datamatrix.decoder; import com.google.zxing.FormatException; import com.google.zxing.common.BitSource; import com.google.zxing.common.DecoderResult; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** * <p>Data Matrix Codes can encode text as bits in one of several modes, and can use multiple modes * in one Data Matrix Code. This class decodes the bits back into text.</p> * * <p>See ISO 16022:2006, 5.2.1 - 5.2.9.2</p> * * @author bbrown@google.com (Brian Brown) * @author Sean Owen */ final class DecodedBitStreamParser { private enum Mode { PAD_ENCODE, // Not really a mode ASCII_ENCODE, C40_ENCODE, TEXT_ENCODE, ANSIX12_ENCODE, EDIFACT_ENCODE, BASE256_ENCODE } /** * See ISO 16022:2006, Annex C Table C.1 * The C40 Basic Character Set (*'s used for placeholders for the shift values) */ private static final char[] C40_BASIC_SET_CHARS = { '*', '*', '*', ' ', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' }; private static final char[] C40_SHIFT2_SET_CHARS = { '!', '"', '#', '$', '%', '&', '\'', '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '?', '@', '[', '\\', ']', '^', '_' }; /** * See ISO 16022:2006, Annex C Table C.2 * The Text Basic Character Set (*'s used for placeholders for the shift values) */ private static final char[] TEXT_BASIC_SET_CHARS = { '*', '*', '*', ' ', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' }; private static final char[] TEXT_SHIFT3_SET_CHARS = { '\'', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '{', '|', '}', '~', (char) 127 }; private DecodedBitStreamParser() { } static DecoderResult decode(byte[] bytes) throws FormatException { BitSource bits = new BitSource(bytes); StringBuilder result = new StringBuilder(100); StringBuilder resultTrailer = new StringBuilder(0); List<byte[]> byteSegments = new ArrayList<byte[]>(1); Mode mode = Mode.ASCII_ENCODE; do { if (mode == Mode.ASCII_ENCODE) { mode = decodeAsciiSegment(bits, result, resultTrailer); } else { switch (mode) { case C40_ENCODE: decodeC40Segment(bits, result); break; case TEXT_ENCODE: decodeTextSegment(bits, result); break; case ANSIX12_ENCODE: decodeAnsiX12Segment(bits, result); break; case EDIFACT_ENCODE: decodeEdifactSegment(bits, result); break; case BASE256_ENCODE: decodeBase256Segment(bits, result, byteSegments); break; default: throw FormatException.getFormatInstance(); } mode = Mode.ASCII_ENCODE; } } while (mode != Mode.PAD_ENCODE && bits.available() > 0); if (resultTrailer.length() > 0) { result.append(resultTrailer.toString()); } return new DecoderResult(bytes, result.toString(), byteSegments.isEmpty() ? null : byteSegments, null); } /** * See ISO 16022:2006, 5.2.3 and Annex C, Table C.2 */ private static Mode decodeAsciiSegment(BitSource bits, StringBuilder result, StringBuilder resultTrailer) throws FormatException { boolean upperShift = false; do { int oneByte = bits.readBits(8); if (oneByte == 0) { throw FormatException.getFormatInstance(); } else if (oneByte <= 128) { // ASCII data (ASCII value + 1) if (upperShift) { oneByte += 128; //upperShift = false; } result.append((char) (oneByte - 1)); return Mode.ASCII_ENCODE; } else if (oneByte == 129) { // Pad return Mode.PAD_ENCODE; } else if (oneByte <= 229) { // 2-digit data 00-99 (Numeric Value + 130) int value = oneByte - 130; if (value < 10) { // padd with '0' for single digit values result.append('0'); } result.append(value); } else if (oneByte == 230) { // Latch to C40 encodation return Mode.C40_ENCODE; } else if (oneByte == 231) { // Latch to Base 256 encodation return Mode.BASE256_ENCODE; } else if (oneByte == 232) { // FNC1 result.append((char) 29); // translate as ASCII 29 } else if (oneByte == 233 || oneByte == 234) { // Structured Append, Reader Programming // Ignore these symbols for now //throw ReaderException.getInstance(); } else if (oneByte == 235) { // Upper Shift (shift to Extended ASCII) upperShift = true; } else if (oneByte == 236) { // 05 Macro result.append("[)>\u001E05\u001D"); resultTrailer.insert(0, "\u001E\u0004"); } else if (oneByte == 237) { // 06 Macro result.append("[)>\u001E06\u001D"); resultTrailer.insert(0, "\u001E\u0004"); } else if (oneByte == 238) { // Latch to ANSI X12 encodation return Mode.ANSIX12_ENCODE; } else if (oneByte == 239) { // Latch to Text encodation return Mode.TEXT_ENCODE; } else if (oneByte == 240) { // Latch to EDIFACT encodation return Mode.EDIFACT_ENCODE; } else if (oneByte == 241) { // ECI Character // TODO(bbrown): I think we need to support ECI //throw ReaderException.getInstance(); // Ignore this symbol for now } else if (oneByte >= 242) { // Not to be used in ASCII encodation // ... but work around encoders that end with 254, latch back to ASCII if (oneByte != 254 || bits.available() != 0) { throw FormatException.getFormatInstance(); } } } while (bits.available() > 0); return Mode.ASCII_ENCODE; } /** * See ISO 16022:2006, 5.2.5 and Annex C, Table C.1 */ private static void decodeC40Segment(BitSource bits, StringBuilder result) throws FormatException { // Three C40 values are encoded in a 16-bit value as // (1600 * C1) + (40 * C2) + C3 + 1 // TODO(bbrown): The Upper Shift with C40 doesn't work in the 4 value scenario all the time boolean upperShift = false; int[] cValues = new int[3]; int shift = 0; do { // If there is only one byte left then it will be encoded as ASCII if (bits.available() == 8) { return; } int firstByte = bits.readBits(8); if (firstByte == 254) { // Unlatch codeword return; } parseTwoBytes(firstByte, bits.readBits(8), cValues); for (int i = 0; i < 3; i++) { int cValue = cValues[i]; switch (shift) { case 0: if (cValue < 3) { shift = cValue + 1; } else if (cValue < C40_BASIC_SET_CHARS.length) { char c40char = C40_BASIC_SET_CHARS[cValue]; if (upperShift) { result.append((char) (c40char + 128)); upperShift = false; } else { result.append(c40char); } } else { throw FormatException.getFormatInstance(); } break; case 1: if (upperShift) { result.append((char) (cValue + 128)); upperShift = false; } else { result.append((char) cValue); } shift = 0; break; case 2: if (cValue < C40_SHIFT2_SET_CHARS.length) { char c40char = C40_SHIFT2_SET_CHARS[cValue]; if (upperShift) { result.append((char) (c40char + 128)); upperShift = false; } else { result.append(c40char); } } else if (cValue == 27) { // FNC1 result.append((char) 29); // translate as ASCII 29 } else if (cValue == 30) { // Upper Shift upperShift = true; } else { throw FormatException.getFormatInstance(); } shift = 0; break; case 3: if (upperShift) { result.append((char) (cValue + 224)); upperShift = false; } else { result.append((char) (cValue + 96)); } shift = 0; break; default: throw FormatException.getFormatInstance(); } } } while (bits.available() > 0); } /** * See ISO 16022:2006, 5.2.6 and Annex C, Table C.2 */ private static void decodeTextSegment(BitSource bits, StringBuilder result) throws FormatException { // Three Text values are encoded in a 16-bit value as // (1600 * C1) + (40 * C2) + C3 + 1 // TODO(bbrown): The Upper Shift with Text doesn't work in the 4 value scenario all the time boolean upperShift = false; int[] cValues = new int[3]; int shift = 0; do { // If there is only one byte left then it will be encoded as ASCII if (bits.available() == 8) { return; } int firstByte = bits.readBits(8); if (firstByte == 254) { // Unlatch codeword return; } parseTwoBytes(firstByte, bits.readBits(8), cValues); for (int i = 0; i < 3; i++) { int cValue = cValues[i]; switch (shift) { case 0: if (cValue < 3) { shift = cValue + 1; } else if (cValue < TEXT_BASIC_SET_CHARS.length) { char textChar = TEXT_BASIC_SET_CHARS[cValue]; if (upperShift) { result.append((char) (textChar + 128)); upperShift = false; } else { result.append(textChar); } } else { throw FormatException.getFormatInstance(); } break; case 1: if (upperShift) { result.append((char) (cValue + 128)); upperShift = false; } else { result.append((char) cValue); } shift = 0; break; case 2: // Shift 2 for Text is the same encoding as C40 if (cValue < C40_SHIFT2_SET_CHARS.length) { char c40char = C40_SHIFT2_SET_CHARS[cValue]; if (upperShift) { result.append((char) (c40char + 128)); upperShift = false; } else { result.append(c40char); } } else if (cValue == 27) { // FNC1 result.append((char) 29); // translate as ASCII 29 } else if (cValue == 30) { // Upper Shift upperShift = true; } else { throw FormatException.getFormatInstance(); } shift = 0; break; case 3: if (cValue < TEXT_SHIFT3_SET_CHARS.length) { char textChar = TEXT_SHIFT3_SET_CHARS[cValue]; if (upperShift) { result.append((char) (textChar + 128)); upperShift = false; } else { result.append(textChar); } shift = 0; } else { throw FormatException.getFormatInstance(); } break; default: throw FormatException.getFormatInstance(); } } } while (bits.available() > 0); } /** * See ISO 16022:2006, 5.2.7 */ private static void decodeAnsiX12Segment(BitSource bits, StringBuilder result) throws FormatException { // Three ANSI X12 values are encoded in a 16-bit value as // (1600 * C1) + (40 * C2) + C3 + 1 int[] cValues = new int[3]; do { // If there is only one byte left then it will be encoded as ASCII if (bits.available() == 8) { return; } int firstByte = bits.readBits(8); if (firstByte == 254) { // Unlatch codeword return; } parseTwoBytes(firstByte, bits.readBits(8), cValues); for (int i = 0; i < 3; i++) { int cValue = cValues[i]; if (cValue == 0) { // X12 segment terminator <CR> result.append('\r'); } else if (cValue == 1) { // X12 segment separator * result.append('*'); } else if (cValue == 2) { // X12 sub-element separator > result.append('>'); } else if (cValue == 3) { // space result.append(' '); } else if (cValue < 14) { // 0 - 9 result.append((char) (cValue + 44)); } else if (cValue < 40) { // A - Z result.append((char) (cValue + 51)); } else { throw FormatException.getFormatInstance(); } } } while (bits.available() > 0); } private static void parseTwoBytes(int firstByte, int secondByte, int[] result) { int fullBitValue = (firstByte << 8) + secondByte - 1; int temp = fullBitValue / 1600; result[0] = temp; fullBitValue -= temp * 1600; temp = fullBitValue / 40; result[1] = temp; result[2] = fullBitValue - temp * 40; } /** * See ISO 16022:2006, 5.2.8 and Annex C Table C.3 */ private static void decodeEdifactSegment(BitSource bits, StringBuilder result) { do { // If there is only two or less bytes left then it will be encoded as ASCII if (bits.available() <= 16) { return; } for (int i = 0; i < 4; i++) { int edifactValue = bits.readBits(6); // Check for the unlatch character if (edifactValue == 0x1F) { // 011111 // Read rest of byte, which should be 0, and stop int bitsLeft = 8 - bits.getBitOffset(); if (bitsLeft != 8) { bits.readBits(bitsLeft); } return; } if ((edifactValue & 0x20) == 0) { // no 1 in the leading (6th) bit edifactValue |= 0x40; // Add a leading 01 to the 6 bit binary value } result.append((char) edifactValue); } } while (bits.available() > 0); } /** * See ISO 16022:2006, 5.2.9 and Annex B, B.2 */ private static void decodeBase256Segment(BitSource bits, StringBuilder result, Collection<byte[]> byteSegments) throws FormatException { // Figure out how long the Base 256 Segment is. int codewordPosition = 1 + bits.getByteOffset(); // position is 1-indexed int d1 = unrandomize255State(bits.readBits(8), codewordPosition++); int count; if (d1 == 0) { // Read the remainder of the symbol count = bits.available() / 8; } else if (d1 < 250) { count = d1; } else { count = 250 * (d1 - 249) + unrandomize255State(bits.readBits(8), codewordPosition++); } // We're seeing NegativeArraySizeException errors from users. if (count < 0) { throw FormatException.getFormatInstance(); } byte[] bytes = new byte[count]; for (int i = 0; i < count; i++) { // Have seen this particular error in the wild, such as at // http://www.bcgen.com/demo/IDAutomationStreamingDataMatrix.aspx?MODE=3&D=Fred&PFMT=3&PT=F&X=0.3&O=0&LM=0.2 if (bits.available() < 8) { throw FormatException.getFormatInstance(); } bytes[i] = (byte) unrandomize255State(bits.readBits(8), codewordPosition++); } byteSegments.add(bytes); try { result.append(new String(bytes, "ISO8859_1")); } catch (UnsupportedEncodingException uee) { throw new IllegalStateException("Platform does not support required encoding: " + uee); } } /** * See ISO 16022:2006, Annex B, B.2 */ private static int unrandomize255State(int randomizedBase256Codeword, int base256CodewordPosition) { int pseudoRandomNumber = ((149 * base256CodewordPosition) % 255) + 1; int tempVariable = randomizedBase256Codeword - pseudoRandomNumber; return tempVariable >= 0 ? tempVariable : tempVariable + 256; } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/datamatrix/decoder/DecodedBitStreamParser.java
Java
epl
17,117
/* * Copyright 2007 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.datamatrix.decoder; import com.google.zxing.ChecksumException; import com.google.zxing.FormatException; import com.google.zxing.common.BitMatrix; import com.google.zxing.common.DecoderResult; import com.google.zxing.common.reedsolomon.GenericGF; import com.google.zxing.common.reedsolomon.ReedSolomonDecoder; import com.google.zxing.common.reedsolomon.ReedSolomonException; /** * <p>The main class which implements Data Matrix Code decoding -- as opposed to locating and extracting * the Data Matrix Code from an image.</p> * * @author bbrown@google.com (Brian Brown) */ public final class Decoder { private final ReedSolomonDecoder rsDecoder; public Decoder() { rsDecoder = new ReedSolomonDecoder(GenericGF.DATA_MATRIX_FIELD_256); } /** * <p>Convenience method that can decode a Data Matrix Code represented as a 2D array of booleans. * "true" is taken to mean a black module.</p> * * @param image booleans representing white/black Data Matrix Code modules * @return text and bytes encoded within the Data Matrix Code * @throws FormatException if the Data Matrix Code cannot be decoded * @throws ChecksumException if error correction fails */ public DecoderResult decode(boolean[][] image) throws FormatException, ChecksumException { int dimension = image.length; BitMatrix bits = new BitMatrix(dimension); for (int i = 0; i < dimension; i++) { for (int j = 0; j < dimension; j++) { if (image[i][j]) { bits.set(j, i); } } } return decode(bits); } /** * <p>Decodes a Data Matrix Code represented as a {@link BitMatrix}. A 1 or "true" is taken * to mean a black module.</p> * * @param bits booleans representing white/black Data Matrix Code modules * @return text and bytes encoded within the Data Matrix Code * @throws FormatException if the Data Matrix Code cannot be decoded * @throws ChecksumException if error correction fails */ public DecoderResult decode(BitMatrix bits) throws FormatException, ChecksumException { // Construct a parser and read version, error-correction level BitMatrixParser parser = new BitMatrixParser(bits); Version version = parser.getVersion(); // Read codewords byte[] codewords = parser.readCodewords(); // Separate into data blocks DataBlock[] dataBlocks = DataBlock.getDataBlocks(codewords, version); int dataBlocksCount = dataBlocks.length; // Count total number of data bytes int totalBytes = 0; for (DataBlock db : dataBlocks) { totalBytes += db.getNumDataCodewords(); } byte[] resultBytes = new byte[totalBytes]; // Error-correct and copy data blocks together into a stream of bytes for (int j = 0; j < dataBlocksCount; j++) { DataBlock dataBlock = dataBlocks[j]; byte[] codewordBytes = dataBlock.getCodewords(); int numDataCodewords = dataBlock.getNumDataCodewords(); correctErrors(codewordBytes, numDataCodewords); for (int i = 0; i < numDataCodewords; i++) { // De-interlace data blocks. resultBytes[i * dataBlocksCount + j] = codewordBytes[i]; } } // Decode the contents of that stream of bytes return DecodedBitStreamParser.decode(resultBytes); } /** * <p>Given data and error-correction codewords received, possibly corrupted by errors, attempts to * correct the errors in-place using Reed-Solomon error correction.</p> * * @param codewordBytes data and error correction codewords * @param numDataCodewords number of codewords that are data bytes * @throws ChecksumException if error correction fails */ private void correctErrors(byte[] codewordBytes, int numDataCodewords) throws ChecksumException { int numCodewords = codewordBytes.length; // First read into an array of ints int[] codewordsInts = new int[numCodewords]; for (int i = 0; i < numCodewords; i++) { codewordsInts[i] = codewordBytes[i] & 0xFF; } int numECCodewords = codewordBytes.length - numDataCodewords; try { rsDecoder.decode(codewordsInts, numECCodewords); } catch (ReedSolomonException ignored) { throw ChecksumException.getChecksumInstance(); } // Copy back into array of bytes -- only need to worry about the bytes that were data // We don't care about errors in the error-correction codewords for (int i = 0; i < numDataCodewords; i++) { codewordBytes[i] = (byte) codewordsInts[i]; } } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/datamatrix/decoder/Decoder.java
Java
epl
5,248
/* * Copyright 2008 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.datamatrix; import com.google.zxing.BarcodeFormat; import com.google.zxing.EncodeHintType; import com.google.zxing.Writer; import com.google.zxing.common.BitMatrix; import com.google.zxing.datamatrix.encoder.DefaultPlacement; import com.google.zxing.Dimension; import com.google.zxing.datamatrix.encoder.ErrorCorrection; import com.google.zxing.datamatrix.encoder.HighLevelEncoder; import com.google.zxing.datamatrix.encoder.SymbolInfo; import com.google.zxing.datamatrix.encoder.SymbolShapeHint; import com.google.zxing.qrcode.encoder.ByteMatrix; import java.util.Map; /** * This object renders a Data Matrix code as a BitMatrix 2D array of greyscale values. * * @author dswitkin@google.com (Daniel Switkin) * @author Guillaume Le Biller Added to zxing lib. */ public final class DataMatrixWriter implements Writer { @Override public BitMatrix encode(String contents, BarcodeFormat format, int width, int height) { return encode(contents, format, width, height, null); } @Override public BitMatrix encode(String contents, BarcodeFormat format, int width, int height, Map<EncodeHintType,?> hints) { if (contents.length() == 0) { throw new IllegalArgumentException("Found empty contents"); } if (format != BarcodeFormat.DATA_MATRIX) { throw new IllegalArgumentException("Can only encode DATA_MATRIX, but got " + format); } if (width < 0 || height < 0) { throw new IllegalArgumentException("Requested dimensions are too small: " + width + 'x' + height); } // Try to get force shape & min / max size SymbolShapeHint shape = SymbolShapeHint.FORCE_NONE; Dimension minSize = null; Dimension maxSize = null; if (hints != null) { SymbolShapeHint requestedShape = (SymbolShapeHint) hints.get(EncodeHintType.DATA_MATRIX_SHAPE); if (requestedShape != null) { shape = requestedShape; } Dimension requestedMinSize = (Dimension) hints.get(EncodeHintType.MIN_SIZE); if (requestedMinSize != null) { minSize = requestedMinSize; } Dimension requestedMaxSize = (Dimension) hints.get(EncodeHintType.MAX_SIZE); if (requestedMaxSize != null) { maxSize = requestedMaxSize; } } //1. step: Data encodation String encoded = HighLevelEncoder.encodeHighLevel(contents, shape, minSize, maxSize); SymbolInfo symbolInfo = SymbolInfo.lookup(encoded.length(), shape, minSize, maxSize, true); //2. step: ECC generation String codewords = ErrorCorrection.encodeECC200(encoded, symbolInfo); //3. step: Module placement in Matrix DefaultPlacement placement = new DefaultPlacement(codewords, symbolInfo.getSymbolDataWidth(), symbolInfo.getSymbolDataHeight()); placement.place(); //4. step: low-level encoding return encodeLowLevel(placement, symbolInfo); } /** * Encode the given symbol info to a bit matrix. * * @param placement The DataMatrix placement. * @param symbolInfo The symbol info to encode. * @return The bit matrix generated. */ private static BitMatrix encodeLowLevel(DefaultPlacement placement, SymbolInfo symbolInfo) { int symbolWidth = symbolInfo.getSymbolDataWidth(); int symbolHeight = symbolInfo.getSymbolDataHeight(); ByteMatrix matrix = new ByteMatrix(symbolInfo.getSymbolWidth(), symbolInfo.getSymbolHeight()); int matrixY = 0; for (int y = 0; y < symbolHeight; y++) { // Fill the top edge with alternate 0 / 1 int matrixX; if ((y % symbolInfo.matrixHeight) == 0) { matrixX = 0; for (int x = 0; x < symbolInfo.getSymbolWidth(); x++) { matrix.set(matrixX, matrixY, (x % 2) == 0); matrixX++; } matrixY++; } matrixX = 0; for (int x = 0; x < symbolWidth; x++) { // Fill the right edge with full 1 if ((x % symbolInfo.matrixWidth) == 0) { matrix.set(matrixX, matrixY, true); matrixX++; } matrix.set(matrixX, matrixY, placement.getBit(x, y)); matrixX++; // Fill the right edge with alternate 0 / 1 if ((x % symbolInfo.matrixWidth) == symbolInfo.matrixWidth - 1) { matrix.set(matrixX, matrixY, (y % 2) == 0); matrixX++; } } matrixY++; // Fill the bottom edge with full 1 if ((y % symbolInfo.matrixHeight) == symbolInfo.matrixHeight - 1) { matrixX = 0; for (int x = 0; x < symbolInfo.getSymbolWidth(); x++) { matrix.set(matrixX, matrixY, true); matrixX++; } matrixY++; } } return convertByteMatrixToBitMatrix(matrix); } /** * Convert the ByteMatrix to BitMatrix. * * @param matrix The input matrix. * @return The output matrix. */ private static BitMatrix convertByteMatrixToBitMatrix(ByteMatrix matrix) { int matrixWidgth = matrix.getWidth(); int matrixHeight = matrix.getHeight(); BitMatrix output = new BitMatrix(matrixWidgth, matrixHeight); output.clear(); for (int i = 0; i < matrixWidgth; i++) { for (int j = 0; j < matrixHeight; j++) { // Zero is white in the bytematrix if (matrix.get(i, j) == 1) { output.set(i, j); } } } return output; } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/datamatrix/DataMatrixWriter.java
Java
epl
5,918
/* * Copyright 2006-2007 Jeremias Maerki. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.datamatrix.encoder; import com.google.zxing.Dimension; import java.nio.charset.Charset; import java.util.Arrays; /** * DataMatrix ECC 200 data encoder following the algorithm described in ISO/IEC 16022:200(E) in * annex S. */ public final class HighLevelEncoder { /** * Padding character */ private static final char PAD = 129; /** * mode latch to C40 encodation mode */ static final char LATCH_TO_C40 = 230; /** * mode latch to Base 256 encodation mode */ static final char LATCH_TO_BASE256 = 231; /** * FNC1 Codeword */ //private static final char FNC1 = 232; /** * Structured Append Codeword */ //private static final char STRUCTURED_APPEND = 233; /** * Reader Programming */ //private static final char READER_PROGRAMMING = 234; /** * Upper Shift */ static final char UPPER_SHIFT = 235; /** * 05 Macro */ private static final char MACRO_05 = 236; /** * 06 Macro */ private static final char MACRO_06 = 237; /** * mode latch to ANSI X.12 encodation mode */ static final char LATCH_TO_ANSIX12 = 238; /** * mode latch to Text encodation mode */ static final char LATCH_TO_TEXT = 239; /** * mode latch to EDIFACT encodation mode */ static final char LATCH_TO_EDIFACT = 240; /** * ECI character (Extended Channel Interpretation) */ //private static final char ECI = 241; /** * Unlatch from C40 encodation */ static final char C40_UNLATCH = 254; /** * Unlatch from X12 encodation */ static final char X12_UNLATCH = 254; /** * 05 Macro header */ private static final String MACRO_05_HEADER = "[)>\u001E05\u001D"; /** * 06 Macro header */ private static final String MACRO_06_HEADER = "[)>\u001E06\u001D"; /** * Macro trailer */ private static final String MACRO_TRAILER = "\u001E\u0004"; static final int ASCII_ENCODATION = 0; static final int C40_ENCODATION = 1; static final int TEXT_ENCODATION = 2; static final int X12_ENCODATION = 3; static final int EDIFACT_ENCODATION = 4; static final int BASE256_ENCODATION = 5; private HighLevelEncoder() { } /** * Converts the message to a byte array using the default encoding (cp437) as defined by the * specification * * @param msg the message * @return the byte array of the message */ public static byte[] getBytesForMessage(String msg) { return msg.getBytes(Charset.forName("cp437")); //See 4.4.3 and annex B of ISO/IEC 15438:2001(E) } private static char randomize253State(char ch, int codewordPosition) { int pseudoRandom = ((149 * codewordPosition) % 253) + 1; int tempVariable = ch + pseudoRandom; return tempVariable <= 254 ? (char) tempVariable : (char) (tempVariable - 254); } /** * Performs message encoding of a DataMatrix message using the algorithm described in annex P * of ISO/IEC 16022:2000(E). * * @param msg the message * @return the encoded message (the char values range from 0 to 255) */ public static String encodeHighLevel(String msg) { return encodeHighLevel(msg, SymbolShapeHint.FORCE_NONE, null, null); } /** * Performs message encoding of a DataMatrix message using the algorithm described in annex P * of ISO/IEC 16022:2000(E). * * @param msg the message * @param shape requested shape. May be {@code SymbolShapeHint.FORCE_NONE}, * {@code SymbolShapeHint.FORCE_SQUARE} or {@code SymbolShapeHint.FORCE_RECTANGLE}. * @param minSize the minimum symbol size constraint or null for no constraint * @param maxSize the maximum symbol size constraint or null for no constraint * @return the encoded message (the char values range from 0 to 255) */ public static String encodeHighLevel(String msg, SymbolShapeHint shape, Dimension minSize, Dimension maxSize) { //the codewords 0..255 are encoded as Unicode characters Encoder[] encoders = { new ASCIIEncoder(), new C40Encoder(), new TextEncoder(), new X12Encoder(), new EdifactEncoder(), new Base256Encoder() }; EncoderContext context = new EncoderContext(msg); context.setSymbolShape(shape); context.setSizeConstraints(minSize, maxSize); if (msg.startsWith(MACRO_05_HEADER) && msg.endsWith(MACRO_TRAILER)) { context.writeCodeword(MACRO_05); context.setSkipAtEnd(2); context.pos += MACRO_05_HEADER.length(); } else if (msg.startsWith(MACRO_06_HEADER) && msg.endsWith(MACRO_TRAILER)) { context.writeCodeword(MACRO_06); context.setSkipAtEnd(2); context.pos += MACRO_06_HEADER.length(); } int encodingMode = ASCII_ENCODATION; //Default mode while (context.hasMoreCharacters()) { encoders[encodingMode].encode(context); if (context.newEncoding >= 0) { encodingMode = context.newEncoding; context.resetEncoderSignal(); } } int len = context.codewords.length(); context.updateSymbolInfo(); int capacity = context.symbolInfo.dataCapacity; if (len < capacity) { if (encodingMode != ASCII_ENCODATION && encodingMode != BASE256_ENCODATION) { context.writeCodeword('\u00fe'); //Unlatch (254) } } //Padding StringBuilder codewords = context.codewords; if (codewords.length() < capacity) { codewords.append(PAD); } while (codewords.length() < capacity) { codewords.append(randomize253State(PAD, codewords.length() + 1)); } return context.codewords.toString(); } static int lookAheadTest(CharSequence msg, int startpos, int currentMode) { if (startpos >= msg.length()) { return currentMode; } float[] charCounts; //step J if (currentMode == ASCII_ENCODATION) { charCounts = new float[]{0, 1, 1, 1, 1, 1.25f}; } else { charCounts = new float[]{1, 2, 2, 2, 2, 2.25f}; charCounts[currentMode] = 0; } int charsProcessed = 0; while (true) { //step K if ((startpos + charsProcessed) == msg.length()) { int min = Integer.MAX_VALUE; byte[] mins = new byte[6]; int[] intCharCounts = new int[6]; min = findMinimums(charCounts, intCharCounts, min, mins); int minCount = getMinimumCount(mins); if (intCharCounts[ASCII_ENCODATION] == min) { return ASCII_ENCODATION; } if (minCount == 1 && mins[BASE256_ENCODATION] > 0) { return BASE256_ENCODATION; } if (minCount == 1 && mins[EDIFACT_ENCODATION] > 0) { return EDIFACT_ENCODATION; } if (minCount == 1 && mins[TEXT_ENCODATION] > 0) { return TEXT_ENCODATION; } if (minCount == 1 && mins[X12_ENCODATION] > 0) { return X12_ENCODATION; } return C40_ENCODATION; } char c = msg.charAt(startpos + charsProcessed); charsProcessed++; //step L if (isDigit(c)) { charCounts[ASCII_ENCODATION] += 0.5; } else if (isExtendedASCII(c)) { charCounts[ASCII_ENCODATION] = (int) Math.ceil(charCounts[ASCII_ENCODATION]); charCounts[ASCII_ENCODATION] += 2; } else { charCounts[ASCII_ENCODATION] = (int) Math.ceil(charCounts[ASCII_ENCODATION]); charCounts[ASCII_ENCODATION]++; } //step M if (isNativeC40(c)) { charCounts[C40_ENCODATION] += 2.0f / 3.0f; } else if (isExtendedASCII(c)) { charCounts[C40_ENCODATION] += 8.0f / 3.0f; } else { charCounts[C40_ENCODATION] += 4.0f / 3.0f; } //step N if (isNativeText(c)) { charCounts[TEXT_ENCODATION] += 2.0f / 3.0f; } else if (isExtendedASCII(c)) { charCounts[TEXT_ENCODATION] += 8.0f / 3.0f; } else { charCounts[TEXT_ENCODATION] += 4.0f / 3.0f; } //step O if (isNativeX12(c)) { charCounts[X12_ENCODATION] += 2.0f / 3.0f; } else if (isExtendedASCII(c)) { charCounts[X12_ENCODATION] += 13.0f / 3.0f; } else { charCounts[X12_ENCODATION] += 10.0f / 3.0f; } //step P if (isNativeEDIFACT(c)) { charCounts[EDIFACT_ENCODATION] += 3.0f / 4.0f; } else if (isExtendedASCII(c)) { charCounts[EDIFACT_ENCODATION] += 17.0f / 4.0f; } else { charCounts[EDIFACT_ENCODATION] += 13.0f / 4.0f; } // step Q if (isSpecialB256(c)) { charCounts[BASE256_ENCODATION] += 4; } else { charCounts[BASE256_ENCODATION]++; } //step R if (charsProcessed >= 4) { int[] intCharCounts = new int[6]; byte[] mins = new byte[6]; findMinimums(charCounts, intCharCounts, Integer.MAX_VALUE, mins); int minCount = getMinimumCount(mins); if (intCharCounts[ASCII_ENCODATION] < intCharCounts[BASE256_ENCODATION] && intCharCounts[ASCII_ENCODATION] < intCharCounts[C40_ENCODATION] && intCharCounts[ASCII_ENCODATION] < intCharCounts[TEXT_ENCODATION] && intCharCounts[ASCII_ENCODATION] < intCharCounts[X12_ENCODATION] && intCharCounts[ASCII_ENCODATION] < intCharCounts[EDIFACT_ENCODATION]) { return ASCII_ENCODATION; } if (intCharCounts[BASE256_ENCODATION] < intCharCounts[ASCII_ENCODATION] || (mins[C40_ENCODATION] + mins[TEXT_ENCODATION] + mins[X12_ENCODATION] + mins[EDIFACT_ENCODATION]) == 0) { return BASE256_ENCODATION; } if (minCount == 1 && mins[EDIFACT_ENCODATION] > 0) { return EDIFACT_ENCODATION; } if (minCount == 1 && mins[TEXT_ENCODATION] > 0) { return TEXT_ENCODATION; } if (minCount == 1 && mins[X12_ENCODATION] > 0) { return X12_ENCODATION; } if (intCharCounts[C40_ENCODATION] + 1 < intCharCounts[ASCII_ENCODATION] && intCharCounts[C40_ENCODATION] + 1 < intCharCounts[BASE256_ENCODATION] && intCharCounts[C40_ENCODATION] + 1 < intCharCounts[EDIFACT_ENCODATION] && intCharCounts[C40_ENCODATION] + 1 < intCharCounts[TEXT_ENCODATION]) { if (intCharCounts[C40_ENCODATION] < intCharCounts[X12_ENCODATION]) { return C40_ENCODATION; } if (intCharCounts[C40_ENCODATION] == intCharCounts[X12_ENCODATION]) { int p = startpos + charsProcessed + 1; while (p < msg.length()) { char tc = msg.charAt(p); if (isX12TermSep(tc)) { return X12_ENCODATION; } if (!isNativeX12(tc)) { break; } p++; } return C40_ENCODATION; } } } } } private static int findMinimums(float[] charCounts, int[] intCharCounts, int min, byte[] mins) { Arrays.fill(mins, (byte) 0); for (int i = 0; i < 6; i++) { intCharCounts[i] = (int) Math.ceil(charCounts[i]); int current = intCharCounts[i]; if (min > current) { min = current; Arrays.fill(mins, (byte) 0); } if (min == current) { mins[i]++; } } return min; } private static int getMinimumCount(byte[] mins) { int minCount = 0; for (int i = 0; i < 6; i++) { minCount += mins[i]; } return minCount; } static boolean isDigit(char ch) { return ch >= '0' && ch <= '9'; } static boolean isExtendedASCII(char ch) { return ch >= 128 && ch <= 255; } private static boolean isNativeC40(char ch) { return (ch == ' ') || (ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'Z'); } private static boolean isNativeText(char ch) { return (ch == ' ') || (ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'z'); } private static boolean isNativeX12(char ch) { return isX12TermSep(ch) || (ch == ' ') || (ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'Z'); } private static boolean isX12TermSep(char ch) { return (ch == '\r') //CR || (ch == '*') || (ch == '>'); } private static boolean isNativeEDIFACT(char ch) { return ch >= ' ' && ch <= '^'; } private static boolean isSpecialB256(char ch) { return false; //TODO NOT IMPLEMENTED YET!!! } /** * Determines the number of consecutive characters that are encodable using numeric compaction. * * @param msg the message * @param startpos the start position within the message * @return the requested character count */ public static int determineConsecutiveDigitCount(CharSequence msg, int startpos) { int count = 0; int len = msg.length(); int idx = startpos; if (idx < len) { char ch = msg.charAt(idx); while (isDigit(ch) && idx < len) { count++; idx++; if (idx < len) { ch = msg.charAt(idx); } } } return count; } static void illegalCharacter(char c) { String hex = Integer.toHexString(c); hex = "0000".substring(0, 4 - hex.length()) + hex; throw new IllegalArgumentException("Illegal character: " + c + " (0x" + hex + ')'); } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/datamatrix/encoder/HighLevelEncoder.java
Java
epl
13,848
/* * Copyright 2006-2007 Jeremias Maerki. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.datamatrix.encoder; final class X12Encoder extends C40Encoder { @Override public int getEncodingMode() { return HighLevelEncoder.X12_ENCODATION; } @Override public void encode(EncoderContext context) { //step C StringBuilder buffer = new StringBuilder(); while (context.hasMoreCharacters()) { char c = context.getCurrentChar(); context.pos++; encodeChar(c, buffer); int count = buffer.length(); if ((count % 3) == 0) { writeNextTriplet(context, buffer); int newMode = HighLevelEncoder.lookAheadTest(context.msg, context.pos, getEncodingMode()); if (newMode != getEncodingMode()) { context.signalEncoderChange(newMode); break; } } } handleEOD(context, buffer); } @Override int encodeChar(char c, StringBuilder sb) { if (c == '\r') { sb.append('\0'); } else if (c == '*') { sb.append('\1'); } else if (c == '>') { sb.append('\2'); } else if (c == ' ') { sb.append('\3'); } else if (c >= '0' && c <= '9') { sb.append((char) (c - 48 + 4)); } else if (c >= 'A' && c <= 'Z') { sb.append((char) (c - 65 + 14)); } else { HighLevelEncoder.illegalCharacter(c); } return 1; } @Override void handleEOD(EncoderContext context, StringBuilder buffer) { context.updateSymbolInfo(); int available = context.symbolInfo.dataCapacity - context.getCodewordCount(); int count = buffer.length(); if (count == 2) { context.writeCodeword(HighLevelEncoder.X12_UNLATCH); context.pos -= 2; context.signalEncoderChange(HighLevelEncoder.ASCII_ENCODATION); } else if (count == 1) { context.pos--; if (available > 1) { context.writeCodeword(HighLevelEncoder.X12_UNLATCH); } //NOP - No unlatch necessary context.signalEncoderChange(HighLevelEncoder.ASCII_ENCODATION); } } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/datamatrix/encoder/X12Encoder.java
Java
epl
2,575
/* * Copyright 2006-2007 Jeremias Maerki. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.datamatrix.encoder; final class Base256Encoder implements Encoder { @Override public int getEncodingMode() { return HighLevelEncoder.BASE256_ENCODATION; } @Override public void encode(EncoderContext context) { StringBuilder buffer = new StringBuilder(); buffer.append('\0'); //Initialize length field while (context.hasMoreCharacters()) { char c = context.getCurrentChar(); buffer.append(c); context.pos++; int newMode = HighLevelEncoder.lookAheadTest(context.msg, context.pos, getEncodingMode()); if (newMode != getEncodingMode()) { context.signalEncoderChange(newMode); break; } } int dataCount = buffer.length() - 1; int lengthFieldSize = 1; int currentSize = context.getCodewordCount() + dataCount + lengthFieldSize; context.updateSymbolInfo(currentSize); boolean mustPad = (context.symbolInfo.dataCapacity - currentSize) > 0; if (context.hasMoreCharacters() || mustPad) { if (dataCount <= 249) { buffer.setCharAt(0, (char) dataCount); } else if (dataCount > 249 && dataCount <= 1555) { buffer.setCharAt(0, (char) ((dataCount / 250) + 249)); buffer.insert(1, (char) (dataCount % 250)); } else { throw new IllegalStateException( "Message length not in valid ranges: " + dataCount); } } for (int i = 0, c = buffer.length(); i < c; i++) { context.writeCodeword(randomize255State( buffer.charAt(i), context.getCodewordCount() + 1)); } } private static char randomize255State(char ch, int codewordPosition) { int pseudoRandom = ((149 * codewordPosition) % 255) + 1; int tempVariable = ch + pseudoRandom; if (tempVariable <= 255) { return (char) tempVariable; } else { return (char) (tempVariable - 256); } } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/datamatrix/encoder/Base256Encoder.java
Java
epl
2,490
/* * Copyright 2007 Jeremias Maerki. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.datamatrix.encoder; /** * Enumeration for DataMatrix symbol shape hint. It can be used to force square or rectangular * symbols. */ public enum SymbolShapeHint { FORCE_NONE, FORCE_SQUARE, FORCE_RECTANGLE, }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/datamatrix/encoder/SymbolShapeHint.java
Java
epl
849
/* * Copyright 2006 Jeremias Maerki * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.datamatrix.encoder; import com.google.zxing.Dimension; /** * Symbol info table for DataMatrix. * * @version $Id$ */ public class SymbolInfo { public static final SymbolInfo[] PROD_SYMBOLS = { new SymbolInfo(false, 3, 5, 8, 8, 1), new SymbolInfo(false, 5, 7, 10, 10, 1), /*rect*/new SymbolInfo(true, 5, 7, 16, 6, 1), new SymbolInfo(false, 8, 10, 12, 12, 1), /*rect*/new SymbolInfo(true, 10, 11, 14, 6, 2), new SymbolInfo(false, 12, 12, 14, 14, 1), /*rect*/new SymbolInfo(true, 16, 14, 24, 10, 1), new SymbolInfo(false, 18, 14, 16, 16, 1), new SymbolInfo(false, 22, 18, 18, 18, 1), /*rect*/new SymbolInfo(true, 22, 18, 16, 10, 2), new SymbolInfo(false, 30, 20, 20, 20, 1), /*rect*/new SymbolInfo(true, 32, 24, 16, 14, 2), new SymbolInfo(false, 36, 24, 22, 22, 1), new SymbolInfo(false, 44, 28, 24, 24, 1), /*rect*/new SymbolInfo(true, 49, 28, 22, 14, 2), new SymbolInfo(false, 62, 36, 14, 14, 4), new SymbolInfo(false, 86, 42, 16, 16, 4), new SymbolInfo(false, 114, 48, 18, 18, 4), new SymbolInfo(false, 144, 56, 20, 20, 4), new SymbolInfo(false, 174, 68, 22, 22, 4), new SymbolInfo(false, 204, 84, 24, 24, 4, 102, 42), new SymbolInfo(false, 280, 112, 14, 14, 16, 140, 56), new SymbolInfo(false, 368, 144, 16, 16, 16, 92, 36), new SymbolInfo(false, 456, 192, 18, 18, 16, 114, 48), new SymbolInfo(false, 576, 224, 20, 20, 16, 144, 56), new SymbolInfo(false, 696, 272, 22, 22, 16, 174, 68), new SymbolInfo(false, 816, 336, 24, 24, 16, 136, 56), new SymbolInfo(false, 1050, 408, 18, 18, 36, 175, 68), new SymbolInfo(false, 1304, 496, 20, 20, 36, 163, 62), new DataMatrixSymbolInfo144(), }; private static SymbolInfo[] symbols = PROD_SYMBOLS; /** * Overrides the symbol info set used by this class. Used for testing purposes. * * @param override the symbol info set to use */ public static void overrideSymbolSet(SymbolInfo[] override) { symbols = override; } private final boolean rectangular; final int dataCapacity; final int errorCodewords; public final int matrixWidth; public final int matrixHeight; private final int dataRegions; int rsBlockData; int rsBlockError; public SymbolInfo(boolean rectangular, int dataCapacity, int errorCodewords, int matrixWidth, int matrixHeight, int dataRegions) { this(rectangular, dataCapacity, errorCodewords, matrixWidth, matrixHeight, dataRegions, dataCapacity, errorCodewords); } private SymbolInfo(boolean rectangular, int dataCapacity, int errorCodewords, int matrixWidth, int matrixHeight, int dataRegions, int rsBlockData, int rsBlockError) { this.rectangular = rectangular; this.dataCapacity = dataCapacity; this.errorCodewords = errorCodewords; this.matrixWidth = matrixWidth; this.matrixHeight = matrixHeight; this.dataRegions = dataRegions; this.rsBlockData = rsBlockData; this.rsBlockError = rsBlockError; } public static SymbolInfo lookup(int dataCodewords) { return lookup(dataCodewords, SymbolShapeHint.FORCE_NONE, true); } public static SymbolInfo lookup(int dataCodewords, SymbolShapeHint shape) { return lookup(dataCodewords, shape, true); } public static SymbolInfo lookup(int dataCodewords, boolean allowRectangular, boolean fail) { SymbolShapeHint shape = allowRectangular ? SymbolShapeHint.FORCE_NONE : SymbolShapeHint.FORCE_SQUARE; return lookup(dataCodewords, shape, fail); } private static SymbolInfo lookup(int dataCodewords, SymbolShapeHint shape, boolean fail) { return lookup(dataCodewords, shape, null, null, fail); } public static SymbolInfo lookup(int dataCodewords, SymbolShapeHint shape, Dimension minSize, Dimension maxSize, boolean fail) { for (SymbolInfo symbol : symbols) { if (shape == SymbolShapeHint.FORCE_SQUARE && symbol.rectangular) { continue; } if (shape == SymbolShapeHint.FORCE_RECTANGLE && !symbol.rectangular) { continue; } if (minSize != null && (symbol.getSymbolWidth() < minSize.getWidth() || symbol.getSymbolHeight() < minSize.getHeight())) { continue; } if (maxSize != null && (symbol.getSymbolWidth() > maxSize.getWidth() || symbol.getSymbolHeight() > maxSize.getHeight())) { continue; } if (dataCodewords <= symbol.dataCapacity) { return symbol; } } if (fail) { throw new IllegalArgumentException( "Can't find a symbol arrangement that matches the message. Data codewords: " + dataCodewords); } return null; } final int getHorizontalDataRegions() { switch (dataRegions) { case 1: return 1; case 2: return 2; case 4: return 2; case 16: return 4; case 36: return 6; default: throw new IllegalStateException("Cannot handle this number of data regions"); } } final int getVerticalDataRegions() { switch (dataRegions) { case 1: return 1; case 2: return 1; case 4: return 2; case 16: return 4; case 36: return 6; default: throw new IllegalStateException("Cannot handle this number of data regions"); } } public final int getSymbolDataWidth() { return getHorizontalDataRegions() * matrixWidth; } public final int getSymbolDataHeight() { return getVerticalDataRegions() * matrixHeight; } public final int getSymbolWidth() { return getSymbolDataWidth() + (getHorizontalDataRegions() * 2); } public final int getSymbolHeight() { return getSymbolDataHeight() + (getVerticalDataRegions() * 2); } public int getCodewordCount() { return dataCapacity + errorCodewords; } public int getInterleavedBlockCount() { return dataCapacity / rsBlockData; } public int getDataLengthForInterleavedBlock(int index) { return rsBlockData; } public final int getErrorLengthForInterleavedBlock(int index) { return rsBlockError; } @Override public final String toString() { StringBuilder sb = new StringBuilder(); sb.append(rectangular ? "Rectangular Symbol:" : "Square Symbol:"); sb.append(" data region ").append(matrixWidth).append('x').append(matrixHeight); sb.append(", symbol size ").append(getSymbolWidth()).append('x').append(getSymbolHeight()); sb.append(", symbol data size ").append(getSymbolDataWidth()).append('x').append(getSymbolDataHeight()); sb.append(", codewords ").append(dataCapacity).append('+').append(errorCodewords); return sb.toString(); } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/datamatrix/encoder/SymbolInfo.java
Java
epl
7,544
/* * Copyright 2006-2007 Jeremias Maerki. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.datamatrix.encoder; interface Encoder { int getEncodingMode(); void encode(EncoderContext context); }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/datamatrix/encoder/Encoder.java
Java
epl
742
/* * Copyright 2006 Jeremias Maerki * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.datamatrix.encoder; final class DataMatrixSymbolInfo144 extends SymbolInfo { DataMatrixSymbolInfo144() { super(false, 1558, 620, 22, 22, 36); this.rsBlockData = -1; //special! see below this.rsBlockError = 62; } @Override public int getInterleavedBlockCount() { return 10; } @Override public int getDataLengthForInterleavedBlock(int index) { return (index <= 8) ? 156 : 155; } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/datamatrix/encoder/DataMatrixSymbolInfo144.java
Java
epl
1,046
/* * Copyright 2006 Jeremias Maerki. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.datamatrix.encoder; import java.util.Arrays; /** * Symbol Character Placement Program. Adapted from Annex M.1 in ISO/IEC 16022:2000(E). */ public class DefaultPlacement { private final String codewords; private final int numrows; private final int numcols; private final byte[] bits; /** * Main constructor * * @param codewords the codewords to place * @param numcols the number of columns * @param numrows the number of rows */ public DefaultPlacement(String codewords, int numcols, int numrows) { this.codewords = codewords; this.numcols = numcols; this.numrows = numrows; this.bits = new byte[numcols * numrows]; Arrays.fill(this.bits, (byte) -1); //Initialize with "not set" value } final int getNumrows() { return numrows; } final int getNumcols() { return numcols; } final byte[] getBits() { return bits; } public final boolean getBit(int col, int row) { return bits[row * numcols + col] == 1; } final void setBit(int col, int row, boolean bit) { bits[row * numcols + col] = bit ? (byte) 1 : (byte) 0; } final boolean hasBit(int col, int row) { return bits[row * numcols + col] >= 0; } public final void place() { int pos = 0; int row = 4; int col = 0; do { /* repeatedly first check for one of the special corner cases, then... */ if ((row == numrows) && (col == 0)) { corner1(pos++); } if ((row == numrows - 2) && (col == 0) && ((numcols % 4) != 0)) { corner2(pos++); } if ((row == numrows - 2) && (col == 0) && (numcols % 8 == 4)) { corner3(pos++); } if ((row == numrows + 4) && (col == 2) && ((numcols % 8) == 0)) { corner4(pos++); } /* sweep upward diagonally, inserting successive characters... */ do { if ((row < numrows) && (col >= 0) && !hasBit(col, row)) { utah(row, col, pos++); } row -= 2; col += 2; } while (row >= 0 && (col < numcols)); row++; col += 3; /* and then sweep downward diagonally, inserting successive characters, ... */ do { if ((row >= 0) && (col < numcols) && !hasBit(col, row)) { utah(row, col, pos++); } row += 2; col -= 2; } while ((row < numrows) && (col >= 0)); row += 3; col++; /* ...until the entire array is scanned */ } while ((row < numrows) || (col < numcols)); /* Lastly, if the lower righthand corner is untouched, fill in fixed pattern */ if (!hasBit(numcols - 1, numrows - 1)) { setBit(numcols - 1, numrows - 1, true); setBit(numcols - 2, numrows - 2, true); } } private void module(int row, int col, int pos, int bit) { if (row < 0) { row += numrows; col += 4 - ((numrows + 4) % 8); } if (col < 0) { col += numcols; row += 4 - ((numcols + 4) % 8); } // Note the conversion: int v = codewords.charAt(pos); v &= 1 << (8 - bit); setBit(col, row, v != 0); } /** * Places the 8 bits of a utah-shaped symbol character in ECC200. * * @param row the row * @param col the column * @param pos character position */ private void utah(int row, int col, int pos) { module(row - 2, col - 2, pos, 1); module(row - 2, col - 1, pos, 2); module(row - 1, col - 2, pos, 3); module(row - 1, col - 1, pos, 4); module(row - 1, col, pos, 5); module(row, col - 2, pos, 6); module(row, col - 1, pos, 7); module(row, col, pos, 8); } private void corner1(int pos) { module(numrows - 1, 0, pos, 1); module(numrows - 1, 1, pos, 2); module(numrows - 1, 2, pos, 3); module(0, numcols - 2, pos, 4); module(0, numcols - 1, pos, 5); module(1, numcols - 1, pos, 6); module(2, numcols - 1, pos, 7); module(3, numcols - 1, pos, 8); } private void corner2(int pos) { module(numrows - 3, 0, pos, 1); module(numrows - 2, 0, pos, 2); module(numrows - 1, 0, pos, 3); module(0, numcols - 4, pos, 4); module(0, numcols - 3, pos, 5); module(0, numcols - 2, pos, 6); module(0, numcols - 1, pos, 7); module(1, numcols - 1, pos, 8); } private void corner3(int pos) { module(numrows - 3, 0, pos, 1); module(numrows - 2, 0, pos, 2); module(numrows - 1, 0, pos, 3); module(0, numcols - 2, pos, 4); module(0, numcols - 1, pos, 5); module(1, numcols - 1, pos, 6); module(2, numcols - 1, pos, 7); module(3, numcols - 1, pos, 8); } private void corner4(int pos) { module(numrows - 1, 0, pos, 1); module(numrows - 1, numcols - 1, pos, 2); module(0, numcols - 3, pos, 3); module(0, numcols - 2, pos, 4); module(0, numcols - 1, pos, 5); module(1, numcols - 3, pos, 6); module(1, numcols - 2, pos, 7); module(1, numcols - 1, pos, 8); } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/datamatrix/encoder/DefaultPlacement.java
Java
epl
5,590
/* * Copyright 2006-2007 Jeremias Maerki. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.datamatrix.encoder; final class ASCIIEncoder implements Encoder { @Override public int getEncodingMode() { return HighLevelEncoder.ASCII_ENCODATION; } @Override public void encode(EncoderContext context) { //step B int n = HighLevelEncoder.determineConsecutiveDigitCount(context.msg, context.pos); if (n >= 2) { context.writeCodeword(encodeASCIIDigits(context.msg.charAt(context.pos), context.msg.charAt(context.pos + 1))); context.pos += 2; } else { char c = context.getCurrentChar(); int newMode = HighLevelEncoder.lookAheadTest(context.msg, context.pos, getEncodingMode()); if (newMode != getEncodingMode()) { switch (newMode) { case HighLevelEncoder.BASE256_ENCODATION: context.writeCodeword(HighLevelEncoder.LATCH_TO_BASE256); context.signalEncoderChange(HighLevelEncoder.BASE256_ENCODATION); return; case HighLevelEncoder.C40_ENCODATION: context.writeCodeword(HighLevelEncoder.LATCH_TO_C40); context.signalEncoderChange(HighLevelEncoder.C40_ENCODATION); return; case HighLevelEncoder.X12_ENCODATION: context.writeCodeword(HighLevelEncoder.LATCH_TO_ANSIX12); context.signalEncoderChange(HighLevelEncoder.X12_ENCODATION); break; case HighLevelEncoder.TEXT_ENCODATION: context.writeCodeword(HighLevelEncoder.LATCH_TO_TEXT); context.signalEncoderChange(HighLevelEncoder.TEXT_ENCODATION); break; case HighLevelEncoder.EDIFACT_ENCODATION: context.writeCodeword(HighLevelEncoder.LATCH_TO_EDIFACT); context.signalEncoderChange(HighLevelEncoder.EDIFACT_ENCODATION); break; default: throw new IllegalStateException("Illegal mode: " + newMode); } } else if (HighLevelEncoder.isExtendedASCII(c)) { context.writeCodeword(HighLevelEncoder.UPPER_SHIFT); context.writeCodeword((char) (c - 128 + 1)); context.pos++; } else { context.writeCodeword((char) (c + 1)); context.pos++; } } } private static char encodeASCIIDigits(char digit1, char digit2) { if (HighLevelEncoder.isDigit(digit1) && HighLevelEncoder.isDigit(digit2)) { int num = (digit1 - 48) * 10 + (digit2 - 48); return (char) (num + 130); } throw new IllegalArgumentException("not digits: " + digit1 + digit2); } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/datamatrix/encoder/ASCIIEncoder.java
Java
epl
3,171
/* * Copyright 2006-2007 Jeremias Maerki. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.datamatrix.encoder; final class EdifactEncoder implements Encoder { @Override public int getEncodingMode() { return HighLevelEncoder.EDIFACT_ENCODATION; } @Override public void encode(EncoderContext context) { //step F StringBuilder buffer = new StringBuilder(); while (context.hasMoreCharacters()) { char c = context.getCurrentChar(); encodeChar(c, buffer); context.pos++; int count = buffer.length(); if (count >= 4) { context.writeCodewords(encodeToCodewords(buffer, 0)); buffer.delete(0, 4); int newMode = HighLevelEncoder.lookAheadTest(context.msg, context.pos, getEncodingMode()); if (newMode != getEncodingMode()) { context.signalEncoderChange(HighLevelEncoder.ASCII_ENCODATION); break; } } } buffer.append((char) 31); //Unlatch handleEOD(context, buffer); } /** * Handle "end of data" situations * * @param context the encoder context * @param buffer the buffer with the remaining encoded characters */ private static void handleEOD(EncoderContext context, CharSequence buffer) { try { int count = buffer.length(); if (count == 0) { return; //Already finished } if (count == 1) { //Only an unlatch at the end context.updateSymbolInfo(); int available = context.symbolInfo.dataCapacity - context.getCodewordCount(); int remaining = context.getRemainingCharacters(); if (remaining == 0 && available <= 2) { return; //No unlatch } } if (count > 4) { throw new IllegalStateException("Count must not exceed 4"); } int restChars = count - 1; String encoded = encodeToCodewords(buffer, 0); boolean endOfSymbolReached = !context.hasMoreCharacters(); boolean restInAscii = endOfSymbolReached && restChars <= 2; if (restChars <= 2) { context.updateSymbolInfo(context.getCodewordCount() + restChars); int available = context.symbolInfo.dataCapacity - context.getCodewordCount(); if (available >= 3) { restInAscii = false; context.updateSymbolInfo(context.getCodewordCount() + encoded.length()); //available = context.symbolInfo.dataCapacity - context.getCodewordCount(); } } if (restInAscii) { context.resetSymbolInfo(); context.pos -= restChars; } else { context.writeCodewords(encoded); } } finally { context.signalEncoderChange(HighLevelEncoder.ASCII_ENCODATION); } } private static void encodeChar(char c, StringBuilder sb) { if (c >= ' ' && c <= '?') { sb.append(c); } else if (c >= '@' && c <= '^') { sb.append((char) (c - 64)); } else { HighLevelEncoder.illegalCharacter(c); } } private static String encodeToCodewords(CharSequence sb, int startPos) { int len = sb.length() - startPos; if (len == 0) { throw new IllegalStateException("StringBuilder must not be empty"); } char c1 = sb.charAt(startPos); char c2 = len >= 2 ? sb.charAt(startPos + 1) : 0; char c3 = len >= 3 ? sb.charAt(startPos + 2) : 0; char c4 = len >= 4 ? sb.charAt(startPos + 3) : 0; int v = (c1 << 18) + (c2 << 12) + (c3 << 6) + c4; char cw1 = (char) ((v >> 16) & 255); char cw2 = (char) ((v >> 8) & 255); char cw3 = (char) (v & 255); StringBuilder res = new StringBuilder(3); res.append(cw1); if (len >= 2) { res.append(cw2); } if (len >= 3) { res.append(cw3); } return res.toString(); } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/datamatrix/encoder/EdifactEncoder.java
Java
epl
4,274
/* * Copyright 2006-2007 Jeremias Maerki. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.datamatrix.encoder; class C40Encoder implements Encoder { @Override public int getEncodingMode() { return HighLevelEncoder.C40_ENCODATION; } @Override public void encode(EncoderContext context) { //step C StringBuilder buffer = new StringBuilder(); while (context.hasMoreCharacters()) { char c = context.getCurrentChar(); context.pos++; int lastCharSize = encodeChar(c, buffer); int unwritten = (buffer.length() / 3) * 2; int curCodewordCount = context.getCodewordCount() + unwritten; context.updateSymbolInfo(curCodewordCount); int available = context.symbolInfo.dataCapacity - curCodewordCount; if (!context.hasMoreCharacters()) { //Avoid having a single C40 value in the last triplet StringBuilder removed = new StringBuilder(); if ((buffer.length() % 3) == 2) { if (available < 2 || available > 2) { lastCharSize = backtrackOneCharacter(context, buffer, removed, lastCharSize); } } while ((buffer.length() % 3) == 1 && ((lastCharSize <= 3 && available != 1) || lastCharSize > 3)) { lastCharSize = backtrackOneCharacter(context, buffer, removed, lastCharSize); } break; } int count = buffer.length(); if ((count % 3) == 0) { int newMode = HighLevelEncoder.lookAheadTest(context.msg, context.pos, getEncodingMode()); if (newMode != getEncodingMode()) { context.signalEncoderChange(newMode); break; } } } handleEOD(context, buffer); } private int backtrackOneCharacter(EncoderContext context, StringBuilder buffer, StringBuilder removed, int lastCharSize) { int count = buffer.length(); buffer.delete(count - lastCharSize, count); context.pos--; char c = context.getCurrentChar(); lastCharSize = encodeChar(c, removed); context.resetSymbolInfo(); //Deal with possible reduction in symbol size return lastCharSize; } static void writeNextTriplet(EncoderContext context, StringBuilder buffer) { context.writeCodewords(encodeToCodewords(buffer, 0)); buffer.delete(0, 3); } /** * Handle "end of data" situations * * @param context the encoder context * @param buffer the buffer with the remaining encoded characters */ void handleEOD(EncoderContext context, StringBuilder buffer) { int unwritten = (buffer.length() / 3) * 2; int rest = buffer.length() % 3; int curCodewordCount = context.getCodewordCount() + unwritten; context.updateSymbolInfo(curCodewordCount); int available = context.symbolInfo.dataCapacity - curCodewordCount; if (rest == 2) { buffer.append('\0'); //Shift 1 while (buffer.length() >= 3) { writeNextTriplet(context, buffer); } if (context.hasMoreCharacters()) { context.writeCodeword(HighLevelEncoder.C40_UNLATCH); } } else if (available == 1 && rest == 1) { while (buffer.length() >= 3) { writeNextTriplet(context, buffer); } if (context.hasMoreCharacters()) { context.writeCodeword(HighLevelEncoder.C40_UNLATCH); } // else no unlatch context.pos--; } else if (rest == 0) { while (buffer.length() >= 3) { writeNextTriplet(context, buffer); } if (available > 0 || context.hasMoreCharacters()) { context.writeCodeword(HighLevelEncoder.C40_UNLATCH); } } else { throw new IllegalStateException("Unexpected case. Please report!"); } context.signalEncoderChange(HighLevelEncoder.ASCII_ENCODATION); } int encodeChar(char c, StringBuilder sb) { if (c == ' ') { sb.append('\3'); return 1; } else if (c >= '0' && c <= '9') { sb.append((char) (c - 48 + 4)); return 1; } else if (c >= 'A' && c <= 'Z') { sb.append((char) (c - 65 + 14)); return 1; } else if (c >= '\0' && c <= '\u001f') { sb.append('\0'); //Shift 1 Set sb.append(c); return 2; } else if (c >= '!' && c <= '/') { sb.append('\1'); //Shift 2 Set sb.append((char) (c - 33)); return 2; } else if (c >= ':' && c <= '@') { sb.append('\1'); //Shift 2 Set sb.append((char) (c - 58 + 15)); return 2; } else if (c >= '[' && c <= '_') { sb.append('\1'); //Shift 2 Set sb.append((char) (c - 91 + 22)); return 2; } else if (c >= '\u0060' && c <= '\u007f') { sb.append('\2'); //Shift 3 Set sb.append((char) (c - 96)); return 2; } else if (c >= '\u0080') { sb.append("\1\u001e"); //Shift 2, Upper Shift int len = 2; len += encodeChar((char) (c - 128), sb); return len; } else { throw new IllegalArgumentException("Illegal character: " + c); } } private static String encodeToCodewords(CharSequence sb, int startPos) { char c1 = sb.charAt(startPos); char c2 = sb.charAt(startPos + 1); char c3 = sb.charAt(startPos + 2); int v = (1600 * c1) + (40 * c2) + c3 + 1; char cw1 = (char) (v / 256); char cw2 = (char) (v % 256); return new String(new char[] {cw1, cw2}); } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/datamatrix/encoder/C40Encoder.java
Java
epl
5,907
/* * Copyright 2006-2007 Jeremias Maerki. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.datamatrix.encoder; final class TextEncoder extends C40Encoder { @Override public int getEncodingMode() { return HighLevelEncoder.TEXT_ENCODATION; } @Override int encodeChar(char c, StringBuilder sb) { if (c == ' ') { sb.append('\3'); return 1; } if (c >= '0' && c <= '9') { sb.append((char) (c - 48 + 4)); return 1; } if (c >= 'a' && c <= 'z') { sb.append((char) (c - 97 + 14)); return 1; } if (c >= '\0' && c <= '\u001f') { sb.append('\0'); //Shift 1 Set sb.append(c); return 2; } if (c >= '!' && c <= '/') { sb.append('\1'); //Shift 2 Set sb.append((char) (c - 33)); return 2; } if (c >= ':' && c <= '@') { sb.append('\1'); //Shift 2 Set sb.append((char) (c - 58 + 15)); return 2; } if (c >= '[' && c <= '_') { sb.append('\1'); //Shift 2 Set sb.append((char) (c - 91 + 22)); return 2; } if (c == '\u0060') { sb.append('\2'); //Shift 3 Set sb.append((char) (c - 96)); return 2; } if (c >= 'A' && c <= 'Z') { sb.append('\2'); //Shift 3 Set sb.append((char) (c - 65 + 1)); return 2; } if (c >= '{' && c <= '\u007f') { sb.append('\2'); //Shift 3 Set sb.append((char) (c - 123 + 27)); return 2; } if (c >= '\u0080') { sb.append("\1\u001e"); //Shift 2, Upper Shift int len = 2; len += encodeChar((char) (c - 128), sb); return len; } HighLevelEncoder.illegalCharacter(c); return -1; } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/datamatrix/encoder/TextEncoder.java
Java
epl
2,217
/* * Copyright 2006-2007 Jeremias Maerki. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.datamatrix.encoder; import com.google.zxing.Dimension; import java.nio.charset.Charset; final class EncoderContext { String msg; private SymbolShapeHint shape; private Dimension minSize; private Dimension maxSize; StringBuilder codewords; int pos; int newEncoding; SymbolInfo symbolInfo; private int skipAtEnd; EncoderContext(String msg) { //From this point on Strings are not Unicode anymore! byte[] msgBinary = msg.getBytes(Charset.forName("ISO-8859-1")); StringBuilder sb = new StringBuilder(msgBinary.length); for (int i = 0, c = msgBinary.length; i < c; i++) { char ch = (char) (msgBinary[i] & 0xff); if (ch == '?' && msg.charAt(i) != '?') { throw new IllegalArgumentException("Message contains characters outside ISO-8859-1 encoding."); } sb.append(ch); } this.msg = sb.toString(); //Not Unicode here! shape = SymbolShapeHint.FORCE_NONE; this.codewords = new StringBuilder(msg.length()); newEncoding = -1; } public void setSymbolShape(SymbolShapeHint shape) { this.shape = shape; } public void setSizeConstraints(Dimension minSize, Dimension maxSize) { this.minSize = minSize; this.maxSize = maxSize; } public String getMessage() { return this.msg; } public void setSkipAtEnd(int count) { this.skipAtEnd = count; } public char getCurrentChar() { return msg.charAt(pos); } public char getCurrent() { return msg.charAt(pos); } public void writeCodewords(String codewords) { this.codewords.append(codewords); } public void writeCodeword(char codeword) { this.codewords.append(codeword); } public int getCodewordCount() { return this.codewords.length(); } public void signalEncoderChange(int encoding) { this.newEncoding = encoding; } public void resetEncoderSignal() { this.newEncoding = -1; } public boolean hasMoreCharacters() { return pos < getTotalMessageCharCount(); } private int getTotalMessageCharCount() { return msg.length() - skipAtEnd; } public int getRemainingCharacters() { return getTotalMessageCharCount() - pos; } public void updateSymbolInfo() { updateSymbolInfo(getCodewordCount()); } public void updateSymbolInfo(int len) { if (this.symbolInfo == null || len > this.symbolInfo.dataCapacity) { this.symbolInfo = SymbolInfo.lookup(len, shape, minSize, maxSize, true); } } public void resetSymbolInfo() { this.symbolInfo = null; } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/datamatrix/encoder/EncoderContext.java
Java
epl
3,147
/* * Copyright 2006 Jeremias Maerki. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.datamatrix.encoder; /** * Error Correction Code for ECC200. */ public final class ErrorCorrection { /** * Lookup table which factors to use for which number of error correction codewords. * See FACTORS. */ private static final int[] FACTOR_SETS = {5, 7, 10, 11, 12, 14, 18, 20, 24, 28, 36, 42, 48, 56, 62, 68}; /** * Precomputed polynomial factors for ECC 200. */ private static final int[][] FACTORS = { {228, 48, 15, 111, 62}, {23, 68, 144, 134, 240, 92, 254}, {28, 24, 185, 166, 223, 248, 116, 255, 110, 61}, {175, 138, 205, 12, 194, 168, 39, 245, 60, 97, 120}, {41, 153, 158, 91, 61, 42, 142, 213, 97, 178, 100, 242}, {156, 97, 192, 252, 95, 9, 157, 119, 138, 45, 18, 186, 83, 185}, {83, 195, 100, 39, 188, 75, 66, 61, 241, 213, 109, 129, 94, 254, 225, 48, 90, 188}, {15, 195, 244, 9, 233, 71, 168, 2, 188, 160, 153, 145, 253, 79, 108, 82, 27, 174, 186, 172}, {52, 190, 88, 205, 109, 39, 176, 21, 155, 197, 251, 223, 155, 21, 5, 172, 254, 124, 12, 181, 184, 96, 50, 193}, {211, 231, 43, 97, 71, 96, 103, 174, 37, 151, 170, 53, 75, 34, 249, 121, 17, 138, 110, 213, 141, 136, 120, 151, 233, 168, 93, 255}, {245, 127, 242, 218, 130, 250, 162, 181, 102, 120, 84, 179, 220, 251, 80, 182, 229, 18, 2, 4, 68, 33, 101, 137, 95, 119, 115, 44, 175, 184, 59, 25, 225, 98, 81, 112}, {77, 193, 137, 31, 19, 38, 22, 153, 247, 105, 122, 2, 245, 133, 242, 8, 175, 95, 100, 9, 167, 105, 214, 111, 57, 121, 21, 1, 253, 57, 54, 101, 248, 202, 69, 50, 150, 177, 226, 5, 9, 5}, {245, 132, 172, 223, 96, 32, 117, 22, 238, 133, 238, 231, 205, 188, 237, 87, 191, 106, 16, 147, 118, 23, 37, 90, 170, 205, 131, 88, 120, 100, 66, 138, 186, 240, 82, 44, 176, 87, 187, 147, 160, 175, 69, 213, 92, 253, 225, 19}, {175, 9, 223, 238, 12, 17, 220, 208, 100, 29, 175, 170, 230, 192, 215, 235, 150, 159, 36, 223, 38, 200, 132, 54, 228, 146, 218, 234, 117, 203, 29, 232, 144, 238, 22, 150, 201, 117, 62, 207, 164, 13, 137, 245, 127, 67, 247, 28, 155, 43, 203, 107, 233, 53, 143, 46}, {242, 93, 169, 50, 144, 210, 39, 118, 202, 188, 201, 189, 143, 108, 196, 37, 185, 112, 134, 230, 245, 63, 197, 190, 250, 106, 185, 221, 175, 64, 114, 71, 161, 44, 147, 6, 27, 218, 51, 63, 87, 10, 40, 130, 188, 17, 163, 31, 176, 170, 4, 107, 232, 7, 94, 166, 224, 124, 86, 47, 11, 204}, {220, 228, 173, 89, 251, 149, 159, 56, 89, 33, 147, 244, 154, 36, 73, 127, 213, 136, 248, 180, 234, 197, 158, 177, 68, 122, 93, 213, 15, 160, 227, 236, 66, 139, 153, 185, 202, 167, 179, 25, 220, 232, 96, 210, 231, 136, 223, 239, 181, 241, 59, 52, 172, 25, 49, 232, 211, 189, 64, 54, 108, 153, 132, 63, 96, 103, 82, 186}}; private static final int MODULO_VALUE = 0x12D; private static final int[] LOG; private static final int[] ALOG; static { //Create log and antilog table LOG = new int[256]; ALOG = new int[255]; int p = 1; for (int i = 0; i < 255; i++) { ALOG[i] = p; LOG[p] = i; p <<= 1; if (p >= 256) { p ^= MODULO_VALUE; } } } private ErrorCorrection() { } /** * Creates the ECC200 error correction for an encoded message. * * @param codewords the codewords * @param symbolInfo information about the symbol to be encoded * @return the codewords with interleaved error correction. */ public static String encodeECC200(String codewords, SymbolInfo symbolInfo) { if (codewords.length() != symbolInfo.dataCapacity) { throw new IllegalArgumentException( "The number of codewords does not match the selected symbol"); } StringBuilder sb = new StringBuilder(symbolInfo.dataCapacity + symbolInfo.errorCodewords); sb.append(codewords); int blockCount = symbolInfo.getInterleavedBlockCount(); if (blockCount == 1) { String ecc = createECCBlock(codewords, symbolInfo.errorCodewords); sb.append(ecc); } else { sb.setLength(sb.capacity()); int[] dataSizes = new int[blockCount]; int[] errorSizes = new int[blockCount]; int[] startPos = new int[blockCount]; for (int i = 0; i < blockCount; i++) { dataSizes[i] = symbolInfo.getDataLengthForInterleavedBlock(i + 1); errorSizes[i] = symbolInfo.getErrorLengthForInterleavedBlock(i + 1); startPos[i] = 0; if (i > 0) { startPos[i] = startPos[i - 1] + dataSizes[i]; } } for (int block = 0; block < blockCount; block++) { StringBuilder temp = new StringBuilder(dataSizes[block]); for (int d = block; d < symbolInfo.dataCapacity; d += blockCount) { temp.append(codewords.charAt(d)); } String ecc = createECCBlock(temp.toString(), errorSizes[block]); int pos = 0; for (int e = block; e < errorSizes[block] * blockCount; e += blockCount) { sb.setCharAt(symbolInfo.dataCapacity + e, ecc.charAt(pos++)); } } } return sb.toString(); } private static String createECCBlock(CharSequence codewords, int numECWords) { return createECCBlock(codewords, 0, codewords.length(), numECWords); } private static String createECCBlock(CharSequence codewords, int start, int len, int numECWords) { int table = -1; for (int i = 0; i < FACTOR_SETS.length; i++) { if (FACTOR_SETS[i] == numECWords) { table = i; break; } } if (table < 0) { throw new IllegalArgumentException( "Illegal number of error correction codewords specified: " + numECWords); } int[] poly = FACTORS[table]; char[] ecc = new char[numECWords]; for (int i = 0; i < numECWords; i++) { ecc[i] = 0; } for (int i = start; i < start + len; i++) { int m = ecc[numECWords - 1] ^ codewords.charAt(i); for (int k = numECWords - 1; k > 0; k--) { if (m != 0 && poly[k] != 0) { ecc[k] = (char) (ecc[k - 1] ^ ALOG[(LOG[m] + LOG[poly[k]]) % 255]); } else { ecc[k] = ecc[k - 1]; } } if (m != 0 && poly[0] != 0) { ecc[0] = (char) ALOG[(LOG[m] + LOG[poly[0]]) % 255]; } else { ecc[0] = 0; } } char[] eccReversed = new char[numECWords]; for (int i = 0; i < numECWords; i++) { eccReversed[i] = ecc[numECWords - i - 1]; } return String.valueOf(eccReversed); } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/datamatrix/encoder/ErrorCorrection.java
Java
epl
7,171
/* * Copyright 2009 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.multi; import com.google.zxing.BinaryBitmap; import com.google.zxing.DecodeHintType; import com.google.zxing.NotFoundException; import com.google.zxing.Result; import java.util.Map; /** * Implementation of this interface attempt to read several barcodes from one image. * * @see com.google.zxing.Reader * @author Sean Owen */ public interface MultipleBarcodeReader { Result[] decodeMultiple(BinaryBitmap image) throws NotFoundException; Result[] decodeMultiple(BinaryBitmap image, Map<DecodeHintType,?> hints) throws NotFoundException; }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/multi/MultipleBarcodeReader.java
Java
epl
1,203
/* * Copyright 2009 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.multi; import com.google.zxing.BinaryBitmap; import com.google.zxing.DecodeHintType; import com.google.zxing.NotFoundException; import com.google.zxing.Reader; import com.google.zxing.ReaderException; import com.google.zxing.Result; import com.google.zxing.ResultPoint; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * <p>Attempts to locate multiple barcodes in an image by repeatedly decoding portion of the image. * After one barcode is found, the areas left, above, right and below the barcode's * {@link ResultPoint}s are scanned, recursively.</p> * * <p>A caller may want to also employ {@link ByQuadrantReader} when attempting to find multiple * 2D barcodes, like QR Codes, in an image, where the presence of multiple barcodes might prevent * detecting any one of them.</p> * * <p>That is, instead of passing a {@link Reader} a caller might pass * {@code new ByQuadrantReader(reader)}.</p> * * @author Sean Owen */ public final class GenericMultipleBarcodeReader implements MultipleBarcodeReader { private static final int MIN_DIMENSION_TO_RECUR = 100; private static final int MAX_DEPTH = 4; private final Reader delegate; public GenericMultipleBarcodeReader(Reader delegate) { this.delegate = delegate; } @Override public Result[] decodeMultiple(BinaryBitmap image) throws NotFoundException { return decodeMultiple(image, null); } @Override public Result[] decodeMultiple(BinaryBitmap image, Map<DecodeHintType,?> hints) throws NotFoundException { List<Result> results = new ArrayList<Result>(); doDecodeMultiple(image, hints, results, 0, 0, 0); if (results.isEmpty()) { throw NotFoundException.getNotFoundInstance(); } return results.toArray(new Result[results.size()]); } private void doDecodeMultiple(BinaryBitmap image, Map<DecodeHintType,?> hints, List<Result> results, int xOffset, int yOffset, int currentDepth) { if (currentDepth > MAX_DEPTH) { return; } Result result; try { result = delegate.decode(image, hints); } catch (ReaderException ignored) { return; } boolean alreadyFound = false; for (Result existingResult : results) { if (existingResult.getText().equals(result.getText())) { alreadyFound = true; break; } } if (!alreadyFound) { results.add(translateResultPoints(result, xOffset, yOffset)); } ResultPoint[] resultPoints = result.getResultPoints(); if (resultPoints == null || resultPoints.length == 0) { return; } int width = image.getWidth(); int height = image.getHeight(); float minX = width; float minY = height; float maxX = 0.0f; float maxY = 0.0f; for (ResultPoint point : resultPoints) { float x = point.getX(); float y = point.getY(); if (x < minX) { minX = x; } if (y < minY) { minY = y; } if (x > maxX) { maxX = x; } if (y > maxY) { maxY = y; } } // Decode left of barcode if (minX > MIN_DIMENSION_TO_RECUR) { doDecodeMultiple(image.crop(0, 0, (int) minX, height), hints, results, xOffset, yOffset, currentDepth + 1); } // Decode above barcode if (minY > MIN_DIMENSION_TO_RECUR) { doDecodeMultiple(image.crop(0, 0, width, (int) minY), hints, results, xOffset, yOffset, currentDepth + 1); } // Decode right of barcode if (maxX < width - MIN_DIMENSION_TO_RECUR) { doDecodeMultiple(image.crop((int) maxX, 0, width - (int) maxX, height), hints, results, xOffset + (int) maxX, yOffset, currentDepth + 1); } // Decode below barcode if (maxY < height - MIN_DIMENSION_TO_RECUR) { doDecodeMultiple(image.crop(0, (int) maxY, width, height - (int) maxY), hints, results, xOffset, yOffset + (int) maxY, currentDepth + 1); } } private static Result translateResultPoints(Result result, int xOffset, int yOffset) { ResultPoint[] oldResultPoints = result.getResultPoints(); if (oldResultPoints == null) { return result; } ResultPoint[] newResultPoints = new ResultPoint[oldResultPoints.length]; for (int i = 0; i < oldResultPoints.length; i++) { ResultPoint oldPoint = oldResultPoints[i]; newResultPoints[i] = new ResultPoint(oldPoint.getX() + xOffset, oldPoint.getY() + yOffset); } Result newResult = new Result(result.getText(), result.getRawBytes(), newResultPoints, result.getBarcodeFormat()); newResult.putAllMetadata(result.getResultMetadata()); return newResult; } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/multi/GenericMultipleBarcodeReader.java
Java
epl
5,661
/* * Copyright 2009 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.multi.qrcode.detector; import com.google.zxing.DecodeHintType; import com.google.zxing.NotFoundException; import com.google.zxing.ResultPoint; import com.google.zxing.ResultPointCallback; import com.google.zxing.common.BitMatrix; import com.google.zxing.qrcode.detector.FinderPattern; import com.google.zxing.qrcode.detector.FinderPatternFinder; import com.google.zxing.qrcode.detector.FinderPatternInfo; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map; /** * <p>This class attempts to find finder patterns in a QR Code. Finder patterns are the square * markers at three corners of a QR Code.</p> * * <p>This class is thread-safe but not reentrant. Each thread must allocate its own object. * * <p>In contrast to {@link FinderPatternFinder}, this class will return an array of all possible * QR code locations in the image.</p> * * <p>Use the TRY_HARDER hint to ask for a more thorough detection.</p> * * @author Sean Owen * @author Hannes Erven */ final class MultiFinderPatternFinder extends FinderPatternFinder { private static final FinderPatternInfo[] EMPTY_RESULT_ARRAY = new FinderPatternInfo[0]; // TODO MIN_MODULE_COUNT and MAX_MODULE_COUNT would be great hints to ask the user for // since it limits the number of regions to decode // max. legal count of modules per QR code edge (177) private static final float MAX_MODULE_COUNT_PER_EDGE = 180; // min. legal count per modules per QR code edge (11) private static final float MIN_MODULE_COUNT_PER_EDGE = 9; /** * More or less arbitrary cutoff point for determining if two finder patterns might belong * to the same code if they differ less than DIFF_MODSIZE_CUTOFF_PERCENT percent in their * estimated modules sizes. */ private static final float DIFF_MODSIZE_CUTOFF_PERCENT = 0.05f; /** * More or less arbitrary cutoff point for determining if two finder patterns might belong * to the same code if they differ less than DIFF_MODSIZE_CUTOFF pixels/module in their * estimated modules sizes. */ private static final float DIFF_MODSIZE_CUTOFF = 0.5f; /** * A comparator that orders FinderPatterns by their estimated module size. */ private static final class ModuleSizeComparator implements Comparator<FinderPattern>, Serializable { @Override public int compare(FinderPattern center1, FinderPattern center2) { float value = center2.getEstimatedModuleSize() - center1.getEstimatedModuleSize(); return value < 0.0 ? -1 : value > 0.0 ? 1 : 0; } } /** * <p>Creates a finder that will search the image for three finder patterns.</p> * * @param image image to search */ MultiFinderPatternFinder(BitMatrix image) { super(image); } MultiFinderPatternFinder(BitMatrix image, ResultPointCallback resultPointCallback) { super(image, resultPointCallback); } /** * @return the 3 best {@link FinderPattern}s from our list of candidates. The "best" are * those that have been detected at least {@link #CENTER_QUORUM} times, and whose module * size differs from the average among those patterns the least * @throws NotFoundException if 3 such finder patterns do not exist */ private FinderPattern[][] selectMutipleBestPatterns() throws NotFoundException { List<FinderPattern> possibleCenters = getPossibleCenters(); int size = possibleCenters.size(); if (size < 3) { // Couldn't find enough finder patterns throw NotFoundException.getNotFoundInstance(); } /* * Begin HE modifications to safely detect multiple codes of equal size */ if (size == 3) { return new FinderPattern[][]{ new FinderPattern[]{ possibleCenters.get(0), possibleCenters.get(1), possibleCenters.get(2) } }; } // Sort by estimated module size to speed up the upcoming checks Collections.sort(possibleCenters, new ModuleSizeComparator()); /* * Now lets start: build a list of tuples of three finder locations that * - feature similar module sizes * - are placed in a distance so the estimated module count is within the QR specification * - have similar distance between upper left/right and left top/bottom finder patterns * - form a triangle with 90° angle (checked by comparing top right/bottom left distance * with pythagoras) * * Note: we allow each point to be used for more than one code region: this might seem * counterintuitive at first, but the performance penalty is not that big. At this point, * we cannot make a good quality decision whether the three finders actually represent * a QR code, or are just by chance layouted so it looks like there might be a QR code there. * So, if the layout seems right, lets have the decoder try to decode. */ List<FinderPattern[]> results = new ArrayList<FinderPattern[]>(); // holder for the results for (int i1 = 0; i1 < (size - 2); i1++) { FinderPattern p1 = possibleCenters.get(i1); if (p1 == null) { continue; } for (int i2 = i1 + 1; i2 < (size - 1); i2++) { FinderPattern p2 = possibleCenters.get(i2); if (p2 == null) { continue; } // Compare the expected module sizes; if they are really off, skip float vModSize12 = (p1.getEstimatedModuleSize() - p2.getEstimatedModuleSize()) / Math.min(p1.getEstimatedModuleSize(), p2.getEstimatedModuleSize()); float vModSize12A = Math.abs(p1.getEstimatedModuleSize() - p2.getEstimatedModuleSize()); if (vModSize12A > DIFF_MODSIZE_CUTOFF && vModSize12 >= DIFF_MODSIZE_CUTOFF_PERCENT) { // break, since elements are ordered by the module size deviation there cannot be // any more interesting elements for the given p1. break; } for (int i3 = i2 + 1; i3 < size; i3++) { FinderPattern p3 = possibleCenters.get(i3); if (p3 == null) { continue; } // Compare the expected module sizes; if they are really off, skip float vModSize23 = (p2.getEstimatedModuleSize() - p3.getEstimatedModuleSize()) / Math.min(p2.getEstimatedModuleSize(), p3.getEstimatedModuleSize()); float vModSize23A = Math.abs(p2.getEstimatedModuleSize() - p3.getEstimatedModuleSize()); if (vModSize23A > DIFF_MODSIZE_CUTOFF && vModSize23 >= DIFF_MODSIZE_CUTOFF_PERCENT) { // break, since elements are ordered by the module size deviation there cannot be // any more interesting elements for the given p1. break; } FinderPattern[] test = {p1, p2, p3}; ResultPoint.orderBestPatterns(test); // Calculate the distances: a = topleft-bottomleft, b=topleft-topright, c = diagonal FinderPatternInfo info = new FinderPatternInfo(test); float dA = ResultPoint.distance(info.getTopLeft(), info.getBottomLeft()); float dC = ResultPoint.distance(info.getTopRight(), info.getBottomLeft()); float dB = ResultPoint.distance(info.getTopLeft(), info.getTopRight()); // Check the sizes float estimatedModuleCount = (dA + dB) / (p1.getEstimatedModuleSize() * 2.0f); if (estimatedModuleCount > MAX_MODULE_COUNT_PER_EDGE || estimatedModuleCount < MIN_MODULE_COUNT_PER_EDGE) { continue; } // Calculate the difference of the edge lengths in percent float vABBC = Math.abs((dA - dB) / Math.min(dA, dB)); if (vABBC >= 0.1f) { continue; } // Calculate the diagonal length by assuming a 90° angle at topleft float dCpy = (float) Math.sqrt(dA * dA + dB * dB); // Compare to the real distance in % float vPyC = Math.abs((dC - dCpy) / Math.min(dC, dCpy)); if (vPyC >= 0.1f) { continue; } // All tests passed! results.add(test); } // end iterate p3 } // end iterate p2 } // end iterate p1 if (!results.isEmpty()) { return results.toArray(new FinderPattern[results.size()][]); } // Nothing found! throw NotFoundException.getNotFoundInstance(); } public FinderPatternInfo[] findMulti(Map<DecodeHintType,?> hints) throws NotFoundException { boolean tryHarder = hints != null && hints.containsKey(DecodeHintType.TRY_HARDER); BitMatrix image = getImage(); int maxI = image.getHeight(); int maxJ = image.getWidth(); // We are looking for black/white/black/white/black modules in // 1:1:3:1:1 ratio; this tracks the number of such modules seen so far // Let's assume that the maximum version QR Code we support takes up 1/4 the height of the // image, and then account for the center being 3 modules in size. This gives the smallest // number of pixels the center could be, so skip this often. When trying harder, look for all // QR versions regardless of how dense they are. int iSkip = (int) (maxI / (MAX_MODULES * 4.0f) * 3); if (iSkip < MIN_SKIP || tryHarder) { iSkip = MIN_SKIP; } int[] stateCount = new int[5]; for (int i = iSkip - 1; i < maxI; i += iSkip) { // Get a row of black/white values stateCount[0] = 0; stateCount[1] = 0; stateCount[2] = 0; stateCount[3] = 0; stateCount[4] = 0; int currentState = 0; for (int j = 0; j < maxJ; j++) { if (image.get(j, i)) { // Black pixel if ((currentState & 1) == 1) { // Counting white pixels currentState++; } stateCount[currentState]++; } else { // White pixel if ((currentState & 1) == 0) { // Counting black pixels if (currentState == 4) { // A winner? if (foundPatternCross(stateCount) && handlePossibleCenter(stateCount, i, j)) { // Yes // Clear state to start looking again currentState = 0; stateCount[0] = 0; stateCount[1] = 0; stateCount[2] = 0; stateCount[3] = 0; stateCount[4] = 0; } else { // No, shift counts back by two stateCount[0] = stateCount[2]; stateCount[1] = stateCount[3]; stateCount[2] = stateCount[4]; stateCount[3] = 1; stateCount[4] = 0; currentState = 3; } } else { stateCount[++currentState]++; } } else { // Counting white pixels stateCount[currentState]++; } } } // for j=... if (foundPatternCross(stateCount)) { handlePossibleCenter(stateCount, i, maxJ); } // end if foundPatternCross } // for i=iSkip-1 ... FinderPattern[][] patternInfo = selectMutipleBestPatterns(); List<FinderPatternInfo> result = new ArrayList<FinderPatternInfo>(); for (FinderPattern[] pattern : patternInfo) { ResultPoint.orderBestPatterns(pattern); result.add(new FinderPatternInfo(pattern)); } if (result.isEmpty()) { return EMPTY_RESULT_ARRAY; } else { return result.toArray(new FinderPatternInfo[result.size()]); } } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/multi/qrcode/detector/MultiFinderPatternFinder.java
Java
epl
12,416
/* * Copyright 2009 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.multi.qrcode.detector; import com.google.zxing.DecodeHintType; import com.google.zxing.NotFoundException; import com.google.zxing.ReaderException; import com.google.zxing.ResultPointCallback; import com.google.zxing.common.BitMatrix; import com.google.zxing.common.DetectorResult; import com.google.zxing.qrcode.detector.Detector; import com.google.zxing.qrcode.detector.FinderPatternInfo; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * <p>Encapsulates logic that can detect one or more QR Codes in an image, even if the QR Code * is rotated or skewed, or partially obscured.</p> * * @author Sean Owen * @author Hannes Erven */ public final class MultiDetector extends Detector { private static final DetectorResult[] EMPTY_DETECTOR_RESULTS = new DetectorResult[0]; public MultiDetector(BitMatrix image) { super(image); } public DetectorResult[] detectMulti(Map<DecodeHintType,?> hints) throws NotFoundException { BitMatrix image = getImage(); ResultPointCallback resultPointCallback = hints == null ? null : (ResultPointCallback) hints.get(DecodeHintType.NEED_RESULT_POINT_CALLBACK); MultiFinderPatternFinder finder = new MultiFinderPatternFinder(image, resultPointCallback); FinderPatternInfo[] infos = finder.findMulti(hints); if (infos.length == 0) { throw NotFoundException.getNotFoundInstance(); } List<DetectorResult> result = new ArrayList<DetectorResult>(); for (FinderPatternInfo info : infos) { try { result.add(processFinderPatternInfo(info)); } catch (ReaderException e) { // ignore } } if (result.isEmpty()) { return EMPTY_DETECTOR_RESULTS; } else { return result.toArray(new DetectorResult[result.size()]); } } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/multi/qrcode/detector/MultiDetector.java
Java
epl
2,421
/* * Copyright 2009 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.multi.qrcode; import com.google.zxing.BarcodeFormat; import com.google.zxing.BinaryBitmap; import com.google.zxing.DecodeHintType; import com.google.zxing.NotFoundException; import com.google.zxing.ReaderException; import com.google.zxing.Result; import com.google.zxing.ResultMetadataType; import com.google.zxing.ResultPoint; import com.google.zxing.common.DecoderResult; import com.google.zxing.common.DetectorResult; import com.google.zxing.multi.MultipleBarcodeReader; import com.google.zxing.multi.qrcode.detector.MultiDetector; import com.google.zxing.qrcode.QRCodeReader; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * This implementation can detect and decode multiple QR Codes in an image. * * @author Sean Owen * @author Hannes Erven */ public final class QRCodeMultiReader extends QRCodeReader implements MultipleBarcodeReader { private static final Result[] EMPTY_RESULT_ARRAY = new Result[0]; @Override public Result[] decodeMultiple(BinaryBitmap image) throws NotFoundException { return decodeMultiple(image, null); } @Override public Result[] decodeMultiple(BinaryBitmap image, Map<DecodeHintType,?> hints) throws NotFoundException { List<Result> results = new ArrayList<Result>(); DetectorResult[] detectorResults = new MultiDetector(image.getBlackMatrix()).detectMulti(hints); for (DetectorResult detectorResult : detectorResults) { try { DecoderResult decoderResult = getDecoder().decode(detectorResult.getBits(), hints); ResultPoint[] points = detectorResult.getPoints(); Result result = new Result(decoderResult.getText(), decoderResult.getRawBytes(), points, BarcodeFormat.QR_CODE); List<byte[]> byteSegments = decoderResult.getByteSegments(); if (byteSegments != null) { result.putMetadata(ResultMetadataType.BYTE_SEGMENTS, byteSegments); } String ecLevel = decoderResult.getECLevel(); if (ecLevel != null) { result.putMetadata(ResultMetadataType.ERROR_CORRECTION_LEVEL, ecLevel); } results.add(result); } catch (ReaderException re) { // ignore and continue } } if (results.isEmpty()) { return EMPTY_RESULT_ARRAY; } else { return results.toArray(new Result[results.size()]); } } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/multi/qrcode/QRCodeMultiReader.java
Java
epl
2,992
/* * Copyright 2009 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.multi; import com.google.zxing.BinaryBitmap; import com.google.zxing.ChecksumException; import com.google.zxing.DecodeHintType; import com.google.zxing.FormatException; import com.google.zxing.NotFoundException; import com.google.zxing.Reader; import com.google.zxing.Result; import java.util.Map; /** * This class attempts to decode a barcode from an image, not by scanning the whole image, * but by scanning subsets of the image. This is important when there may be multiple barcodes in * an image, and detecting a barcode may find parts of multiple barcode and fail to decode * (e.g. QR Codes). Instead this scans the four quadrants of the image -- and also the center * 'quadrant' to cover the case where a barcode is found in the center. * * @see GenericMultipleBarcodeReader */ public final class ByQuadrantReader implements Reader { private final Reader delegate; public ByQuadrantReader(Reader delegate) { this.delegate = delegate; } @Override public Result decode(BinaryBitmap image) throws NotFoundException, ChecksumException, FormatException { return decode(image, null); } @Override public Result decode(BinaryBitmap image, Map<DecodeHintType,?> hints) throws NotFoundException, ChecksumException, FormatException { int width = image.getWidth(); int height = image.getHeight(); int halfWidth = width / 2; int halfHeight = height / 2; BinaryBitmap topLeft = image.crop(0, 0, halfWidth, halfHeight); try { return delegate.decode(topLeft, hints); } catch (NotFoundException re) { // continue } BinaryBitmap topRight = image.crop(halfWidth, 0, halfWidth, halfHeight); try { return delegate.decode(topRight, hints); } catch (NotFoundException re) { // continue } BinaryBitmap bottomLeft = image.crop(0, halfHeight, halfWidth, halfHeight); try { return delegate.decode(bottomLeft, hints); } catch (NotFoundException re) { // continue } BinaryBitmap bottomRight = image.crop(halfWidth, halfHeight, halfWidth, halfHeight); try { return delegate.decode(bottomRight, hints); } catch (NotFoundException re) { // continue } int quarterWidth = halfWidth / 2; int quarterHeight = halfHeight / 2; BinaryBitmap center = image.crop(quarterWidth, quarterHeight, halfWidth, halfHeight); return delegate.decode(center, hints); } @Override public void reset() { delegate.reset(); } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/multi/ByQuadrantReader.java
Java
epl
3,115
/* * Copyright 2013 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing; /** * A wrapper implementation of {@link LuminanceSource} which inverts the luminances it returns -- black becomes * white and vice versa, and each value becomes (255-value). * * @author Sean Owen */ public final class InvertedLuminanceSource extends LuminanceSource { private final LuminanceSource delegate; public InvertedLuminanceSource(LuminanceSource delegate) { super(delegate.getWidth(), delegate.getHeight()); this.delegate = delegate; } @Override public byte[] getRow(int y, byte[] row) { row = delegate.getRow(y, row); int width = getWidth(); for (int i = 0; i < width; i++) { row[i] = (byte) (255 - (row[i] & 0xFF)); } return row; } @Override public byte[] getMatrix() { byte[] matrix = delegate.getMatrix(); int length = getWidth() * getHeight(); byte[] invertedMatrix = new byte[length]; for (int i = 0; i < length; i++) { invertedMatrix[i] = (byte) (255 - (matrix[i] & 0xFF)); } return invertedMatrix; } @Override public boolean isCropSupported() { return delegate.isCropSupported(); } @Override public LuminanceSource crop(int left, int top, int width, int height) { return new InvertedLuminanceSource(delegate.crop(left, top, width, height)); } @Override public boolean isRotateSupported() { return delegate.isRotateSupported(); } /** * @return original delegate {@link LuminanceSource} since invert undoes itself */ @Override public LuminanceSource invert() { return delegate; } @Override public LuminanceSource rotateCounterClockwise() { return new InvertedLuminanceSource(delegate.rotateCounterClockwise()); } @Override public LuminanceSource rotateCounterClockwise45() { return new InvertedLuminanceSource(delegate.rotateCounterClockwise45()); } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/InvertedLuminanceSource.java
Java
epl
2,463
/* * Copyright 2009 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing; import com.google.zxing.common.BitArray; import com.google.zxing.common.BitMatrix; /** * This class hierarchy provides a set of methods to convert luminance data to 1 bit data. * It allows the algorithm to vary polymorphically, for example allowing a very expensive * thresholding technique for servers and a fast one for mobile. It also permits the implementation * to vary, e.g. a JNI version for Android and a Java fallback version for other platforms. * * @author dswitkin@google.com (Daniel Switkin) */ public abstract class Binarizer { private final LuminanceSource source; protected Binarizer(LuminanceSource source) { this.source = source; } public final LuminanceSource getLuminanceSource() { return source; } /** * Converts one row of luminance data to 1 bit data. May actually do the conversion, or return * cached data. Callers should assume this method is expensive and call it as seldom as possible. * This method is intended for decoding 1D barcodes and may choose to apply sharpening. * For callers which only examine one row of pixels at a time, the same BitArray should be reused * and passed in with each call for performance. However it is legal to keep more than one row * at a time if needed. * * @param y The row to fetch, 0 <= y < bitmap height. * @param row An optional preallocated array. If null or too small, it will be ignored. * If used, the Binarizer will call BitArray.clear(). Always use the returned object. * @return The array of bits for this row (true means black). */ public abstract BitArray getBlackRow(int y, BitArray row) throws NotFoundException; /** * Converts a 2D array of luminance data to 1 bit data. As above, assume this method is expensive * and do not call it repeatedly. This method is intended for decoding 2D barcodes and may or * may not apply sharpening. Therefore, a row from this matrix may not be identical to one * fetched using getBlackRow(), so don't mix and match between them. * * @return The 2D array of bits for the image (true means black). */ public abstract BitMatrix getBlackMatrix() throws NotFoundException; /** * Creates a new object with the same type as this Binarizer implementation, but with pristine * state. This is needed because Binarizer implementations may be stateful, e.g. keeping a cache * of 1 bit data. See Effective Java for why we can't use Java's clone() method. * * @param source The LuminanceSource this Binarizer will operate on. * @return A new concrete Binarizer implementation object. */ public abstract Binarizer createBinarizer(LuminanceSource source); public final int getWidth() { return source.getWidth(); } public final int getHeight() { return source.getHeight(); } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/Binarizer.java
Java
epl
3,451
/* * Copyright 2007 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing; /** * Thrown when a barcode was successfully detected, but some aspect of * the content did not conform to the barcode's format rules. This could have * been due to a mis-detection. * * @author Sean Owen */ public final class FormatException extends ReaderException { private static final FormatException instance = new FormatException(); private FormatException() { // do nothing } public static FormatException getFormatInstance() { return instance; } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/FormatException.java
Java
epl
1,109
/* * Copyright 2007 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing; /** * The general exception class throw when something goes wrong during decoding of a barcode. * This includes, but is not limited to, failing checksums / error correction algorithms, being * unable to locate finder timing patterns, and so on. * * @author Sean Owen */ public abstract class ReaderException extends Exception { ReaderException() { // do nothing } // Prevent stack traces from being taken // srowen says: huh, my IDE is saying this is not an override. native methods can't be overridden? // This, at least, does not hurt. Because we use a singleton pattern here, it doesn't matter anyhow. @Override public final Throwable fillInStackTrace() { return null; } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/ReaderException.java
Java
epl
1,335
/* * Copyright 2009 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.common.detector; import com.google.zxing.NotFoundException; import com.google.zxing.ResultPoint; import com.google.zxing.common.BitMatrix; /** * <p>A somewhat generic detector that looks for a barcode-like rectangular region within an image. * It looks within a mostly white region of an image for a region of black and white, but mostly * black. It returns the four corners of the region, as best it can determine.</p> * * @author Sean Owen */ public final class MonochromeRectangleDetector { private static final int MAX_MODULES = 32; private final BitMatrix image; public MonochromeRectangleDetector(BitMatrix image) { this.image = image; } /** * <p>Detects a rectangular region of black and white -- mostly black -- with a region of mostly * white, in an image.</p> * * @return {@link ResultPoint}[] describing the corners of the rectangular region. The first and * last points are opposed on the diagonal, as are the second and third. The first point will be * the topmost point and the last, the bottommost. The second point will be leftmost and the * third, the rightmost * @throws NotFoundException if no Data Matrix Code can be found */ public ResultPoint[] detect() throws NotFoundException { int height = image.getHeight(); int width = image.getWidth(); int halfHeight = height >> 1; int halfWidth = width >> 1; int deltaY = Math.max(1, height / (MAX_MODULES << 3)); int deltaX = Math.max(1, width / (MAX_MODULES << 3)); int top = 0; int bottom = height; int left = 0; int right = width; ResultPoint pointA = findCornerFromCenter(halfWidth, 0, left, right, halfHeight, -deltaY, top, bottom, halfWidth >> 1); top = (int) pointA.getY() - 1; ResultPoint pointB = findCornerFromCenter(halfWidth, -deltaX, left, right, halfHeight, 0, top, bottom, halfHeight >> 1); left = (int) pointB.getX() - 1; ResultPoint pointC = findCornerFromCenter(halfWidth, deltaX, left, right, halfHeight, 0, top, bottom, halfHeight >> 1); right = (int) pointC.getX() + 1; ResultPoint pointD = findCornerFromCenter(halfWidth, 0, left, right, halfHeight, deltaY, top, bottom, halfWidth >> 1); bottom = (int) pointD.getY() + 1; // Go try to find point A again with better information -- might have been off at first. pointA = findCornerFromCenter(halfWidth, 0, left, right, halfHeight, -deltaY, top, bottom, halfWidth >> 2); return new ResultPoint[] { pointA, pointB, pointC, pointD }; } /** * Attempts to locate a corner of the barcode by scanning up, down, left or right from a center * point which should be within the barcode. * * @param centerX center's x component (horizontal) * @param deltaX same as deltaY but change in x per step instead * @param left minimum value of x * @param right maximum value of x * @param centerY center's y component (vertical) * @param deltaY change in y per step. If scanning up this is negative; down, positive; * left or right, 0 * @param top minimum value of y to search through (meaningless when di == 0) * @param bottom maximum value of y * @param maxWhiteRun maximum run of white pixels that can still be considered to be within * the barcode * @return a {@link com.google.zxing.ResultPoint} encapsulating the corner that was found * @throws NotFoundException if such a point cannot be found */ private ResultPoint findCornerFromCenter(int centerX, int deltaX, int left, int right, int centerY, int deltaY, int top, int bottom, int maxWhiteRun) throws NotFoundException { int[] lastRange = null; for (int y = centerY, x = centerX; y < bottom && y >= top && x < right && x >= left; y += deltaY, x += deltaX) { int[] range; if (deltaX == 0) { // horizontal slices, up and down range = blackWhiteRange(y, maxWhiteRun, left, right, true); } else { // vertical slices, left and right range = blackWhiteRange(x, maxWhiteRun, top, bottom, false); } if (range == null) { if (lastRange == null) { throw NotFoundException.getNotFoundInstance(); } // lastRange was found if (deltaX == 0) { int lastY = y - deltaY; if (lastRange[0] < centerX) { if (lastRange[1] > centerX) { // straddle, choose one or the other based on direction return new ResultPoint(deltaY > 0 ? lastRange[0] : lastRange[1], lastY); } return new ResultPoint(lastRange[0], lastY); } else { return new ResultPoint(lastRange[1], lastY); } } else { int lastX = x - deltaX; if (lastRange[0] < centerY) { if (lastRange[1] > centerY) { return new ResultPoint(lastX, deltaX < 0 ? lastRange[0] : lastRange[1]); } return new ResultPoint(lastX, lastRange[0]); } else { return new ResultPoint(lastX, lastRange[1]); } } } lastRange = range; } throw NotFoundException.getNotFoundInstance(); } /** * Computes the start and end of a region of pixels, either horizontally or vertically, that could * be part of a Data Matrix barcode. * * @param fixedDimension if scanning horizontally, this is the row (the fixed vertical location) * where we are scanning. If scanning vertically it's the column, the fixed horizontal location * @param maxWhiteRun largest run of white pixels that can still be considered part of the * barcode region * @param minDim minimum pixel location, horizontally or vertically, to consider * @param maxDim maximum pixel location, horizontally or vertically, to consider * @param horizontal if true, we're scanning left-right, instead of up-down * @return int[] with start and end of found range, or null if no such range is found * (e.g. only white was found) */ private int[] blackWhiteRange(int fixedDimension, int maxWhiteRun, int minDim, int maxDim, boolean horizontal) { int center = (minDim + maxDim) >> 1; // Scan left/up first int start = center; while (start >= minDim) { if (horizontal ? image.get(start, fixedDimension) : image.get(fixedDimension, start)) { start--; } else { int whiteRunStart = start; do { start--; } while (start >= minDim && !(horizontal ? image.get(start, fixedDimension) : image.get(fixedDimension, start))); int whiteRunSize = whiteRunStart - start; if (start < minDim || whiteRunSize > maxWhiteRun) { start = whiteRunStart; break; } } } start++; // Then try right/down int end = center; while (end < maxDim) { if (horizontal ? image.get(end, fixedDimension) : image.get(fixedDimension, end)) { end++; } else { int whiteRunStart = end; do { end++; } while (end < maxDim && !(horizontal ? image.get(end, fixedDimension) : image.get(fixedDimension, end))); int whiteRunSize = end - whiteRunStart; if (end >= maxDim || whiteRunSize > maxWhiteRun) { end = whiteRunStart; break; } } } end--; return end > start ? new int[]{start, end} : null; } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/common/detector/MonochromeRectangleDetector.java
Java
epl
8,399
/* * Copyright 2010 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.common.detector; import com.google.zxing.NotFoundException; import com.google.zxing.ResultPoint; import com.google.zxing.common.BitMatrix; /** * <p> * Detects a candidate barcode-like rectangular region within an image. It * starts around the center of the image, increases the size of the candidate * region until it finds a white rectangular region. By keeping track of the * last black points it encountered, it determines the corners of the barcode. * </p> * * @author David Olivier */ public final class WhiteRectangleDetector { private static final int INIT_SIZE = 30; private static final int CORR = 1; private final BitMatrix image; private final int height; private final int width; private final int leftInit; private final int rightInit; private final int downInit; private final int upInit; /** * @throws NotFoundException if image is too small */ public WhiteRectangleDetector(BitMatrix image) throws NotFoundException { this.image = image; height = image.getHeight(); width = image.getWidth(); leftInit = (width - INIT_SIZE) >> 1; rightInit = (width + INIT_SIZE) >> 1; upInit = (height - INIT_SIZE) >> 1; downInit = (height + INIT_SIZE) >> 1; if (upInit < 0 || leftInit < 0 || downInit >= height || rightInit >= width) { throw NotFoundException.getNotFoundInstance(); } } /** * @throws NotFoundException if image is too small */ public WhiteRectangleDetector(BitMatrix image, int initSize, int x, int y) throws NotFoundException { this.image = image; height = image.getHeight(); width = image.getWidth(); int halfsize = initSize >> 1; leftInit = x - halfsize; rightInit = x + halfsize; upInit = y - halfsize; downInit = y + halfsize; if (upInit < 0 || leftInit < 0 || downInit >= height || rightInit >= width) { throw NotFoundException.getNotFoundInstance(); } } /** * <p> * Detects a candidate barcode-like rectangular region within an image. It * starts around the center of the image, increases the size of the candidate * region until it finds a white rectangular region. * </p> * * @return {@link ResultPoint}[] describing the corners of the rectangular * region. The first and last points are opposed on the diagonal, as * are the second and third. The first point will be the topmost * point and the last, the bottommost. The second point will be * leftmost and the third, the rightmost * @throws NotFoundException if no Data Matrix Code can be found */ public ResultPoint[] detect() throws NotFoundException { int left = leftInit; int right = rightInit; int up = upInit; int down = downInit; boolean sizeExceeded = false; boolean aBlackPointFoundOnBorder = true; boolean atLeastOneBlackPointFoundOnBorder = false; while (aBlackPointFoundOnBorder) { aBlackPointFoundOnBorder = false; // ..... // . | // ..... boolean rightBorderNotWhite = true; while (rightBorderNotWhite && right < width) { rightBorderNotWhite = containsBlackPoint(up, down, right, false); if (rightBorderNotWhite) { right++; aBlackPointFoundOnBorder = true; } } if (right >= width) { sizeExceeded = true; break; } // ..... // . . // .___. boolean bottomBorderNotWhite = true; while (bottomBorderNotWhite && down < height) { bottomBorderNotWhite = containsBlackPoint(left, right, down, true); if (bottomBorderNotWhite) { down++; aBlackPointFoundOnBorder = true; } } if (down >= height) { sizeExceeded = true; break; } // ..... // | . // ..... boolean leftBorderNotWhite = true; while (leftBorderNotWhite && left >= 0) { leftBorderNotWhite = containsBlackPoint(up, down, left, false); if (leftBorderNotWhite) { left--; aBlackPointFoundOnBorder = true; } } if (left < 0) { sizeExceeded = true; break; } // .___. // . . // ..... boolean topBorderNotWhite = true; while (topBorderNotWhite && up >= 0) { topBorderNotWhite = containsBlackPoint(left, right, up, true); if (topBorderNotWhite) { up--; aBlackPointFoundOnBorder = true; } } if (up < 0) { sizeExceeded = true; break; } if (aBlackPointFoundOnBorder) { atLeastOneBlackPointFoundOnBorder = true; } } if (!sizeExceeded && atLeastOneBlackPointFoundOnBorder) { int maxSize = right - left; ResultPoint z = null; for (int i = 1; i < maxSize; i++) { z = getBlackPointOnSegment(left, down - i, left + i, down); if (z != null) { break; } } if (z == null) { throw NotFoundException.getNotFoundInstance(); } ResultPoint t = null; //go down right for (int i = 1; i < maxSize; i++) { t = getBlackPointOnSegment(left, up + i, left + i, up); if (t != null) { break; } } if (t == null) { throw NotFoundException.getNotFoundInstance(); } ResultPoint x = null; //go down left for (int i = 1; i < maxSize; i++) { x = getBlackPointOnSegment(right, up + i, right - i, up); if (x != null) { break; } } if (x == null) { throw NotFoundException.getNotFoundInstance(); } ResultPoint y = null; //go up left for (int i = 1; i < maxSize; i++) { y = getBlackPointOnSegment(right, down - i, right - i, down); if (y != null) { break; } } if (y == null) { throw NotFoundException.getNotFoundInstance(); } return centerEdges(y, z, x, t); } else { throw NotFoundException.getNotFoundInstance(); } } private ResultPoint getBlackPointOnSegment(float aX, float aY, float bX, float bY) { int dist = MathUtils.round(MathUtils.distance(aX, aY, bX, bY)); float xStep = (bX - aX) / dist; float yStep = (bY - aY) / dist; for (int i = 0; i < dist; i++) { int x = MathUtils.round(aX + i * xStep); int y = MathUtils.round(aY + i * yStep); if (image.get(x, y)) { return new ResultPoint(x, y); } } return null; } /** * recenters the points of a constant distance towards the center * * @param y bottom most point * @param z left most point * @param x right most point * @param t top most point * @return {@link ResultPoint}[] describing the corners of the rectangular * region. The first and last points are opposed on the diagonal, as * are the second and third. The first point will be the topmost * point and the last, the bottommost. The second point will be * leftmost and the third, the rightmost */ private ResultPoint[] centerEdges(ResultPoint y, ResultPoint z, ResultPoint x, ResultPoint t) { // // t t // z x // x OR z // y y // float yi = y.getX(); float yj = y.getY(); float zi = z.getX(); float zj = z.getY(); float xi = x.getX(); float xj = x.getY(); float ti = t.getX(); float tj = t.getY(); if (yi < width / 2.0f) { return new ResultPoint[]{ new ResultPoint(ti - CORR, tj + CORR), new ResultPoint(zi + CORR, zj + CORR), new ResultPoint(xi - CORR, xj - CORR), new ResultPoint(yi + CORR, yj - CORR)}; } else { return new ResultPoint[]{ new ResultPoint(ti + CORR, tj + CORR), new ResultPoint(zi + CORR, zj - CORR), new ResultPoint(xi - CORR, xj + CORR), new ResultPoint(yi - CORR, yj - CORR)}; } } /** * Determines whether a segment contains a black point * * @param a min value of the scanned coordinate * @param b max value of the scanned coordinate * @param fixed value of fixed coordinate * @param horizontal set to true if scan must be horizontal, false if vertical * @return true if a black point has been found, else false. */ private boolean containsBlackPoint(int a, int b, int fixed, boolean horizontal) { if (horizontal) { for (int x = a; x <= b; x++) { if (image.get(x, fixed)) { return true; } } } else { for (int y = a; y <= b; y++) { if (image.get(fixed, y)) { return true; } } } return false; } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/common/detector/WhiteRectangleDetector.java
Java
epl
9,487
/* * Copyright 2012 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.common.detector; public final class MathUtils { private MathUtils() { } /** * Ends up being a bit faster than {@link Math#round(float)}. This merely rounds its * argument to the nearest int, where x.5 rounds up to x+1. */ public static int round(float d) { return (int) (d + 0.5f); } public static float distance(float aX, float aY, float bX, float bY) { float xDiff = aX - bX; float yDiff = aY - bY; return (float) Math.sqrt(xDiff * xDiff + yDiff * yDiff); } public static float distance(int aX, int aY, int bX, int bY) { int xDiff = aX - bX; int yDiff = aY - bY; return (float) Math.sqrt(xDiff * xDiff + yDiff * yDiff); } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/common/detector/MathUtils.java
Java
epl
1,311
/* * Copyright 2007 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.common; /** * <p>A simple, fast array of bits, represented compactly by an array of ints internally.</p> * * @author Sean Owen */ public final class BitArray { private int[] bits; private int size; public BitArray() { this.size = 0; this.bits = new int[1]; } public BitArray(int size) { this.size = size; this.bits = makeArray(size); } public int getSize() { return size; } public int getSizeInBytes() { return (size + 7) >> 3; } private void ensureCapacity(int size) { if (size > bits.length << 5) { int[] newBits = makeArray(size); System.arraycopy(bits, 0, newBits, 0, bits.length); this.bits = newBits; } } /** * @param i bit to get * @return true iff bit i is set */ public boolean get(int i) { return (bits[i >> 5] & (1 << (i & 0x1F))) != 0; } /** * Sets bit i. * * @param i bit to set */ public void set(int i) { bits[i >> 5] |= 1 << (i & 0x1F); } /** * Flips bit i. * * @param i bit to set */ public void flip(int i) { bits[i >> 5] ^= 1 << (i & 0x1F); } /** * @param from first bit to check * @return index of first bit that is set, starting from the given index, or size if none are set * at or beyond this given index * @see #getNextUnset(int) */ public int getNextSet(int from) { if (from >= size) { return size; } int bitsOffset = from >> 5; int currentBits = bits[bitsOffset]; // mask off lesser bits first currentBits &= ~((1 << (from & 0x1F)) - 1); while (currentBits == 0) { if (++bitsOffset == bits.length) { return size; } currentBits = bits[bitsOffset]; } int result = (bitsOffset << 5) + Integer.numberOfTrailingZeros(currentBits); return result > size ? size : result; } /** * @see #getNextSet(int) */ public int getNextUnset(int from) { if (from >= size) { return size; } int bitsOffset = from >> 5; int currentBits = ~bits[bitsOffset]; // mask off lesser bits first currentBits &= ~((1 << (from & 0x1F)) - 1); while (currentBits == 0) { if (++bitsOffset == bits.length) { return size; } currentBits = ~bits[bitsOffset]; } int result = (bitsOffset << 5) + Integer.numberOfTrailingZeros(currentBits); return result > size ? size : result; } /** * Sets a block of 32 bits, starting at bit i. * * @param i first bit to set * @param newBits the new value of the next 32 bits. Note again that the least-significant bit * corresponds to bit i, the next-least-significant to i+1, and so on. */ public void setBulk(int i, int newBits) { bits[i >> 5] = newBits; } /** * Sets a range of bits. * * @param start start of range, inclusive. * @param end end of range, exclusive */ public void setRange(int start, int end) { if (end < start) { throw new IllegalArgumentException(); } if (end == start) { return; } end--; // will be easier to treat this as the last actually set bit -- inclusive int firstInt = start >> 5; int lastInt = end >> 5; for (int i = firstInt; i <= lastInt; i++) { int firstBit = i > firstInt ? 0 : start & 0x1F; int lastBit = i < lastInt ? 31 : end & 0x1F; int mask; if (firstBit == 0 && lastBit == 31) { mask = -1; } else { mask = 0; for (int j = firstBit; j <= lastBit; j++) { mask |= 1 << j; } } bits[i] |= mask; } } /** * Clears all bits (sets to false). */ public void clear() { int max = bits.length; for (int i = 0; i < max; i++) { bits[i] = 0; } } /** * Efficient method to check if a range of bits is set, or not set. * * @param start start of range, inclusive. * @param end end of range, exclusive * @param value if true, checks that bits in range are set, otherwise checks that they are not set * @return true iff all bits are set or not set in range, according to value argument * @throws IllegalArgumentException if end is less than or equal to start */ public boolean isRange(int start, int end, boolean value) { if (end < start) { throw new IllegalArgumentException(); } if (end == start) { return true; // empty range matches } end--; // will be easier to treat this as the last actually set bit -- inclusive int firstInt = start >> 5; int lastInt = end >> 5; for (int i = firstInt; i <= lastInt; i++) { int firstBit = i > firstInt ? 0 : start & 0x1F; int lastBit = i < lastInt ? 31 : end & 0x1F; int mask; if (firstBit == 0 && lastBit == 31) { mask = -1; } else { mask = 0; for (int j = firstBit; j <= lastBit; j++) { mask |= 1 << j; } } // Return false if we're looking for 1s and the masked bits[i] isn't all 1s (that is, // equals the mask, or we're looking for 0s and the masked portion is not all 0s if ((bits[i] & mask) != (value ? mask : 0)) { return false; } } return true; } public void appendBit(boolean bit) { ensureCapacity(size + 1); if (bit) { bits[size >> 5] |= 1 << (size & 0x1F); } size++; } /** * Appends the least-significant bits, from value, in order from most-significant to * least-significant. For example, appending 6 bits from 0x000001E will append the bits * 0, 1, 1, 1, 1, 0 in that order. */ public void appendBits(int value, int numBits) { if (numBits < 0 || numBits > 32) { throw new IllegalArgumentException("Num bits must be between 0 and 32"); } ensureCapacity(size + numBits); for (int numBitsLeft = numBits; numBitsLeft > 0; numBitsLeft--) { appendBit(((value >> (numBitsLeft - 1)) & 0x01) == 1); } } public void appendBitArray(BitArray other) { int otherSize = other.size; ensureCapacity(size + otherSize); for (int i = 0; i < otherSize; i++) { appendBit(other.get(i)); } } public void xor(BitArray other) { if (bits.length != other.bits.length) { throw new IllegalArgumentException("Sizes don't match"); } for (int i = 0; i < bits.length; i++) { // The last byte could be incomplete (i.e. not have 8 bits in // it) but there is no problem since 0 XOR 0 == 0. bits[i] ^= other.bits[i]; } } /** * * @param bitOffset first bit to start writing * @param array array to write into. Bytes are written most-significant byte first. This is the opposite * of the internal representation, which is exposed by {@link #getBitArray()} * @param offset position in array to start writing * @param numBytes how many bytes to write */ public void toBytes(int bitOffset, byte[] array, int offset, int numBytes) { for (int i = 0; i < numBytes; i++) { int theByte = 0; for (int j = 0; j < 8; j++) { if (get(bitOffset)) { theByte |= 1 << (7 - j); } bitOffset++; } array[offset + i] = (byte) theByte; } } /** * @return underlying array of ints. The first element holds the first 32 bits, and the least * significant bit is bit 0. */ public int[] getBitArray() { return bits; } /** * Reverses all bits in the array. */ public void reverse() { int[] newBits = new int[bits.length]; int size = this.size; for (int i = 0; i < size; i++) { if (get(size - i - 1)) { newBits[i >> 5] |= 1 << (i & 0x1F); } } bits = newBits; } private static int[] makeArray(int size) { return new int[(size + 31) >> 5]; } @Override public String toString() { StringBuilder result = new StringBuilder(size); for (int i = 0; i < size; i++) { if ((i & 0x07) == 0) { result.append(' '); } result.append(get(i) ? 'X' : '.'); } return result.toString(); } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/common/BitArray.java
Java
epl
8,960
/* * Copyright 2007 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.common.reedsolomon; /** * <p>This class contains utility methods for performing mathematical operations over * the Galois Fields. Operations use a given primitive polynomial in calculations.</p> * * <p>Throughout this package, elements of the GF are represented as an {@code int} * for convenience and speed (but at the cost of memory). * </p> * * @author Sean Owen * @author David Olivier */ public final class GenericGF { public static final GenericGF AZTEC_DATA_12 = new GenericGF(0x1069, 4096, 1); // x^12 + x^6 + x^5 + x^3 + 1 public static final GenericGF AZTEC_DATA_10 = new GenericGF(0x409, 1024, 1); // x^10 + x^3 + 1 public static final GenericGF AZTEC_DATA_6 = new GenericGF(0x43, 64, 1); // x^6 + x + 1 public static final GenericGF AZTEC_PARAM = new GenericGF(0x13, 16, 1); // x^4 + x + 1 public static final GenericGF QR_CODE_FIELD_256 = new GenericGF(0x011D, 256, 0); // x^8 + x^4 + x^3 + x^2 + 1 public static final GenericGF DATA_MATRIX_FIELD_256 = new GenericGF(0x012D, 256, 1); // x^8 + x^5 + x^3 + x^2 + 1 public static final GenericGF AZTEC_DATA_8 = DATA_MATRIX_FIELD_256; public static final GenericGF MAXICODE_FIELD_64 = AZTEC_DATA_6; private static final int INITIALIZATION_THRESHOLD = 0; private int[] expTable; private int[] logTable; private GenericGFPoly zero; private GenericGFPoly one; private final int size; private final int primitive; private final int generatorBase; private boolean initialized = false; /** * Create a representation of GF(size) using the given primitive polynomial. * * @param primitive irreducible polynomial whose coefficients are represented by * the bits of an int, where the least-significant bit represents the constant * coefficient * @param size the size of the field * @param b the factor b in the generator polynomial can be 0- or 1-based * (g(x) = (x+a^b)(x+a^(b+1))...(x+a^(b+2t-1))). * In most cases it should be 1, but for QR code it is 0. */ public GenericGF(int primitive, int size, int b) { this.primitive = primitive; this.size = size; this.generatorBase = b; if (size <= INITIALIZATION_THRESHOLD) { initialize(); } } private void initialize() { expTable = new int[size]; logTable = new int[size]; int x = 1; for (int i = 0; i < size; i++) { expTable[i] = x; x <<= 1; // x = x * 2; we're assuming the generator alpha is 2 if (x >= size) { x ^= primitive; x &= size-1; } } for (int i = 0; i < size-1; i++) { logTable[expTable[i]] = i; } // logTable[0] == 0 but this should never be used zero = new GenericGFPoly(this, new int[]{0}); one = new GenericGFPoly(this, new int[]{1}); initialized = true; } private void checkInit() { if (!initialized) { initialize(); } } GenericGFPoly getZero() { checkInit(); return zero; } GenericGFPoly getOne() { checkInit(); return one; } /** * @return the monomial representing coefficient * x^degree */ GenericGFPoly buildMonomial(int degree, int coefficient) { checkInit(); if (degree < 0) { throw new IllegalArgumentException(); } if (coefficient == 0) { return zero; } int[] coefficients = new int[degree + 1]; coefficients[0] = coefficient; return new GenericGFPoly(this, coefficients); } /** * Implements both addition and subtraction -- they are the same in GF(size). * * @return sum/difference of a and b */ static int addOrSubtract(int a, int b) { return a ^ b; } /** * @return 2 to the power of a in GF(size) */ int exp(int a) { checkInit(); return expTable[a]; } /** * @return base 2 log of a in GF(size) */ int log(int a) { checkInit(); if (a == 0) { throw new IllegalArgumentException(); } return logTable[a]; } /** * @return multiplicative inverse of a */ int inverse(int a) { checkInit(); if (a == 0) { throw new ArithmeticException(); } return expTable[size - logTable[a] - 1]; } /** * @return product of a and b in GF(size) */ int multiply(int a, int b) { checkInit(); if (a == 0 || b == 0) { return 0; } return expTable[(logTable[a] + logTable[b]) % (size - 1)]; } public int getSize() { return size; } public int getGeneratorBase() { return generatorBase; } @Override public String toString() { return "GF(0x" + Integer.toHexString(primitive) + ',' + size + ')'; } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/common/reedsolomon/GenericGF.java
Java
epl
5,233
/* * Copyright 2007 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.common.reedsolomon; /** * <p>Thrown when an exception occurs during Reed-Solomon decoding, such as when * there are too many errors to correct.</p> * * @author Sean Owen */ public final class ReedSolomonException extends Exception { public ReedSolomonException(String message) { super(message); } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/common/reedsolomon/ReedSolomonException.java
Java
epl
938
/* * Copyright 2008 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.common.reedsolomon; import java.util.ArrayList; import java.util.List; /** * <p>Implements Reed-Solomon enbcoding, as the name implies.</p> * * @author Sean Owen * @author William Rucklidge */ public final class ReedSolomonEncoder { private final GenericGF field; private final List<GenericGFPoly> cachedGenerators; public ReedSolomonEncoder(GenericGF field) { this.field = field; this.cachedGenerators = new ArrayList<GenericGFPoly>(); cachedGenerators.add(new GenericGFPoly(field, new int[]{1})); } private GenericGFPoly buildGenerator(int degree) { if (degree >= cachedGenerators.size()) { GenericGFPoly lastGenerator = cachedGenerators.get(cachedGenerators.size() - 1); for (int d = cachedGenerators.size(); d <= degree; d++) { GenericGFPoly nextGenerator = lastGenerator.multiply( new GenericGFPoly(field, new int[] { 1, field.exp(d - 1 + field.getGeneratorBase()) })); cachedGenerators.add(nextGenerator); lastGenerator = nextGenerator; } } return cachedGenerators.get(degree); } public void encode(int[] toEncode, int ecBytes) { if (ecBytes == 0) { throw new IllegalArgumentException("No error correction bytes"); } int dataBytes = toEncode.length - ecBytes; if (dataBytes <= 0) { throw new IllegalArgumentException("No data bytes provided"); } GenericGFPoly generator = buildGenerator(ecBytes); int[] infoCoefficients = new int[dataBytes]; System.arraycopy(toEncode, 0, infoCoefficients, 0, dataBytes); GenericGFPoly info = new GenericGFPoly(field, infoCoefficients); info = info.multiplyByMonomial(ecBytes, 1); GenericGFPoly remainder = info.divide(generator)[1]; int[] coefficients = remainder.getCoefficients(); int numZeroCoefficients = ecBytes - coefficients.length; for (int i = 0; i < numZeroCoefficients; i++) { toEncode[dataBytes + i] = 0; } System.arraycopy(coefficients, 0, toEncode, dataBytes + numZeroCoefficients, coefficients.length); } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/common/reedsolomon/ReedSolomonEncoder.java
Java
epl
2,674
/* * Copyright 2007 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.common.reedsolomon; /** * <p>Implements Reed-Solomon decoding, as the name implies.</p> * * <p>The algorithm will not be explained here, but the following references were helpful * in creating this implementation:</p> * * <ul> * <li>Bruce Maggs. * <a href="http://www.cs.cmu.edu/afs/cs.cmu.edu/project/pscico-guyb/realworld/www/rs_decode.ps"> * "Decoding Reed-Solomon Codes"</a> (see discussion of Forney's Formula)</li> * <li>J.I. Hall. <a href="www.mth.msu.edu/~jhall/classes/codenotes/GRS.pdf"> * "Chapter 5. Generalized Reed-Solomon Codes"</a> * (see discussion of Euclidean algorithm)</li> * </ul> * * <p>Much credit is due to William Rucklidge since portions of this code are an indirect * port of his C++ Reed-Solomon implementation.</p> * * @author Sean Owen * @author William Rucklidge * @author sanfordsquires */ public final class ReedSolomonDecoder { private final GenericGF field; public ReedSolomonDecoder(GenericGF field) { this.field = field; } /** * <p>Decodes given set of received codewords, which include both data and error-correction * codewords. Really, this means it uses Reed-Solomon to detect and correct errors, in-place, * in the input.</p> * * @param received data and error-correction codewords * @param twoS number of error-correction codewords available * @throws ReedSolomonException if decoding fails for any reason */ public void decode(int[] received, int twoS) throws ReedSolomonException { GenericGFPoly poly = new GenericGFPoly(field, received); int[] syndromeCoefficients = new int[twoS]; boolean noError = true; for (int i = 0; i < twoS; i++) { int eval = poly.evaluateAt(field.exp(i + field.getGeneratorBase())); syndromeCoefficients[syndromeCoefficients.length - 1 - i] = eval; if (eval != 0) { noError = false; } } if (noError) { return; } GenericGFPoly syndrome = new GenericGFPoly(field, syndromeCoefficients); GenericGFPoly[] sigmaOmega = runEuclideanAlgorithm(field.buildMonomial(twoS, 1), syndrome, twoS); GenericGFPoly sigma = sigmaOmega[0]; GenericGFPoly omega = sigmaOmega[1]; int[] errorLocations = findErrorLocations(sigma); int[] errorMagnitudes = findErrorMagnitudes(omega, errorLocations); for (int i = 0; i < errorLocations.length; i++) { int position = received.length - 1 - field.log(errorLocations[i]); if (position < 0) { throw new ReedSolomonException("Bad error location"); } received[position] = GenericGF.addOrSubtract(received[position], errorMagnitudes[i]); } } public GenericGFPoly[] runEuclideanAlgorithm(GenericGFPoly a, GenericGFPoly b, int R) throws ReedSolomonException { // Assume a's degree is >= b's if (a.getDegree() < b.getDegree()) { GenericGFPoly temp = a; a = b; b = temp; } GenericGFPoly rLast = a; GenericGFPoly r = b; GenericGFPoly tLast = field.getZero(); GenericGFPoly t = field.getOne(); // Run Euclidean algorithm until r's degree is less than R/2 while (r.getDegree() >= R / 2) { GenericGFPoly rLastLast = rLast; GenericGFPoly tLastLast = tLast; rLast = r; tLast = t; // Divide rLastLast by rLast, with quotient in q and remainder in r if (rLast.isZero()) { // Oops, Euclidean algorithm already terminated? throw new ReedSolomonException("r_{i-1} was zero"); } r = rLastLast; GenericGFPoly q = field.getZero(); int denominatorLeadingTerm = rLast.getCoefficient(rLast.getDegree()); int dltInverse = field.inverse(denominatorLeadingTerm); while (r.getDegree() >= rLast.getDegree() && !r.isZero()) { int degreeDiff = r.getDegree() - rLast.getDegree(); int scale = field.multiply(r.getCoefficient(r.getDegree()), dltInverse); q = q.addOrSubtract(field.buildMonomial(degreeDiff, scale)); r = r.addOrSubtract(rLast.multiplyByMonomial(degreeDiff, scale)); } t = q.multiply(tLast).addOrSubtract(tLastLast); if (r.getDegree() >= rLast.getDegree()) { throw new IllegalStateException("Division algorithm failed to reduce polynomial?"); } } int sigmaTildeAtZero = t.getCoefficient(0); if (sigmaTildeAtZero == 0) { throw new ReedSolomonException("sigmaTilde(0) was zero"); } int inverse = field.inverse(sigmaTildeAtZero); GenericGFPoly sigma = t.multiply(inverse); GenericGFPoly omega = r.multiply(inverse); return new GenericGFPoly[]{sigma, omega}; } private int[] findErrorLocations(GenericGFPoly errorLocator) throws ReedSolomonException { // This is a direct application of Chien's search int numErrors = errorLocator.getDegree(); if (numErrors == 1) { // shortcut return new int[] { errorLocator.getCoefficient(1) }; } int[] result = new int[numErrors]; int e = 0; for (int i = 1; i < field.getSize() && e < numErrors; i++) { if (errorLocator.evaluateAt(i) == 0) { result[e] = field.inverse(i); e++; } } if (e != numErrors) { throw new ReedSolomonException("Error locator degree does not match number of roots"); } return result; } private int[] findErrorMagnitudes(GenericGFPoly errorEvaluator, int[] errorLocations) { // This is directly applying Forney's Formula int s = errorLocations.length; int[] result = new int[s]; for (int i = 0; i < s; i++) { int xiInverse = field.inverse(errorLocations[i]); int denominator = 1; for (int j = 0; j < s; j++) { if (i != j) { //denominator = field.multiply(denominator, // GenericGF.addOrSubtract(1, field.multiply(errorLocations[j], xiInverse))); // Above should work but fails on some Apple and Linux JDKs due to a Hotspot bug. // Below is a funny-looking workaround from Steven Parkes int term = field.multiply(errorLocations[j], xiInverse); int termPlus1 = (term & 0x1) == 0 ? term | 1 : term & ~1; denominator = field.multiply(denominator, termPlus1); } } result[i] = field.multiply(errorEvaluator.evaluateAt(xiInverse), field.inverse(denominator)); if (field.getGeneratorBase() != 0) { result[i] = field.multiply(result[i], xiInverse); } } return result; } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/common/reedsolomon/ReedSolomonDecoder.java
Java
epl
7,053
/* * Copyright 2007 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.common.reedsolomon; /** * <p>Represents a polynomial whose coefficients are elements of a GF. * Instances of this class are immutable.</p> * * <p>Much credit is due to William Rucklidge since portions of this code are an indirect * port of his C++ Reed-Solomon implementation.</p> * * @author Sean Owen */ final class GenericGFPoly { private final GenericGF field; private final int[] coefficients; /** * @param field the {@link GenericGF} instance representing the field to use * to perform computations * @param coefficients coefficients as ints representing elements of GF(size), arranged * from most significant (highest-power term) coefficient to least significant * @throws IllegalArgumentException if argument is null or empty, * or if leading coefficient is 0 and this is not a * constant polynomial (that is, it is not the monomial "0") */ GenericGFPoly(GenericGF field, int[] coefficients) { if (coefficients.length == 0) { throw new IllegalArgumentException(); } this.field = field; int coefficientsLength = coefficients.length; if (coefficientsLength > 1 && coefficients[0] == 0) { // Leading term must be non-zero for anything except the constant polynomial "0" int firstNonZero = 1; while (firstNonZero < coefficientsLength && coefficients[firstNonZero] == 0) { firstNonZero++; } if (firstNonZero == coefficientsLength) { this.coefficients = field.getZero().coefficients; } else { this.coefficients = new int[coefficientsLength - firstNonZero]; System.arraycopy(coefficients, firstNonZero, this.coefficients, 0, this.coefficients.length); } } else { this.coefficients = coefficients; } } int[] getCoefficients() { return coefficients; } /** * @return degree of this polynomial */ int getDegree() { return coefficients.length - 1; } /** * @return true iff this polynomial is the monomial "0" */ boolean isZero() { return coefficients[0] == 0; } /** * @return coefficient of x^degree term in this polynomial */ int getCoefficient(int degree) { return coefficients[coefficients.length - 1 - degree]; } /** * @return evaluation of this polynomial at a given point */ int evaluateAt(int a) { if (a == 0) { // Just return the x^0 coefficient return getCoefficient(0); } int size = coefficients.length; if (a == 1) { // Just the sum of the coefficients int result = 0; for (int coefficient : coefficients) { result = GenericGF.addOrSubtract(result, coefficient); } return result; } int result = coefficients[0]; for (int i = 1; i < size; i++) { result = GenericGF.addOrSubtract(field.multiply(a, result), coefficients[i]); } return result; } GenericGFPoly addOrSubtract(GenericGFPoly other) { if (!field.equals(other.field)) { throw new IllegalArgumentException("GenericGFPolys do not have same GenericGF field"); } if (isZero()) { return other; } if (other.isZero()) { return this; } int[] smallerCoefficients = this.coefficients; int[] largerCoefficients = other.coefficients; if (smallerCoefficients.length > largerCoefficients.length) { int[] temp = smallerCoefficients; smallerCoefficients = largerCoefficients; largerCoefficients = temp; } int[] sumDiff = new int[largerCoefficients.length]; int lengthDiff = largerCoefficients.length - smallerCoefficients.length; // Copy high-order terms only found in higher-degree polynomial's coefficients System.arraycopy(largerCoefficients, 0, sumDiff, 0, lengthDiff); for (int i = lengthDiff; i < largerCoefficients.length; i++) { sumDiff[i] = GenericGF.addOrSubtract(smallerCoefficients[i - lengthDiff], largerCoefficients[i]); } return new GenericGFPoly(field, sumDiff); } GenericGFPoly multiply(GenericGFPoly other) { if (!field.equals(other.field)) { throw new IllegalArgumentException("GenericGFPolys do not have same GenericGF field"); } if (isZero() || other.isZero()) { return field.getZero(); } int[] aCoefficients = this.coefficients; int aLength = aCoefficients.length; int[] bCoefficients = other.coefficients; int bLength = bCoefficients.length; int[] product = new int[aLength + bLength - 1]; for (int i = 0; i < aLength; i++) { int aCoeff = aCoefficients[i]; for (int j = 0; j < bLength; j++) { product[i + j] = GenericGF.addOrSubtract(product[i + j], field.multiply(aCoeff, bCoefficients[j])); } } return new GenericGFPoly(field, product); } GenericGFPoly multiply(int scalar) { if (scalar == 0) { return field.getZero(); } if (scalar == 1) { return this; } int size = coefficients.length; int[] product = new int[size]; for (int i = 0; i < size; i++) { product[i] = field.multiply(coefficients[i], scalar); } return new GenericGFPoly(field, product); } GenericGFPoly multiplyByMonomial(int degree, int coefficient) { if (degree < 0) { throw new IllegalArgumentException(); } if (coefficient == 0) { return field.getZero(); } int size = coefficients.length; int[] product = new int[size + degree]; for (int i = 0; i < size; i++) { product[i] = field.multiply(coefficients[i], coefficient); } return new GenericGFPoly(field, product); } GenericGFPoly[] divide(GenericGFPoly other) { if (!field.equals(other.field)) { throw new IllegalArgumentException("GenericGFPolys do not have same GenericGF field"); } if (other.isZero()) { throw new IllegalArgumentException("Divide by 0"); } GenericGFPoly quotient = field.getZero(); GenericGFPoly remainder = this; int denominatorLeadingTerm = other.getCoefficient(other.getDegree()); int inverseDenominatorLeadingTerm = field.inverse(denominatorLeadingTerm); while (remainder.getDegree() >= other.getDegree() && !remainder.isZero()) { int degreeDifference = remainder.getDegree() - other.getDegree(); int scale = field.multiply(remainder.getCoefficient(remainder.getDegree()), inverseDenominatorLeadingTerm); GenericGFPoly term = other.multiplyByMonomial(degreeDifference, scale); GenericGFPoly iterationQuotient = field.buildMonomial(degreeDifference, scale); quotient = quotient.addOrSubtract(iterationQuotient); remainder = remainder.addOrSubtract(term); } return new GenericGFPoly[] { quotient, remainder }; } @Override public String toString() { StringBuilder result = new StringBuilder(8 * getDegree()); for (int degree = getDegree(); degree >= 0; degree--) { int coefficient = getCoefficient(degree); if (coefficient != 0) { if (coefficient < 0) { result.append(" - "); coefficient = -coefficient; } else { if (result.length() > 0) { result.append(" + "); } } if (degree == 0 || coefficient != 1) { int alphaPower = field.log(coefficient); if (alphaPower == 0) { result.append('1'); } else if (alphaPower == 1) { result.append('a'); } else { result.append("a^"); result.append(alphaPower); } } if (degree != 0) { if (degree == 1) { result.append('x'); } else { result.append("x^"); result.append(degree); } } } } return result.toString(); } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/common/reedsolomon/GenericGFPoly.java
Java
epl
8,410
/* * Copyright 2007 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.common; import com.google.zxing.NotFoundException; /** * @author Sean Owen */ public final class DefaultGridSampler extends GridSampler { @Override public BitMatrix sampleGrid(BitMatrix image, int dimensionX, int dimensionY, float p1ToX, float p1ToY, float p2ToX, float p2ToY, float p3ToX, float p3ToY, float p4ToX, float p4ToY, float p1FromX, float p1FromY, float p2FromX, float p2FromY, float p3FromX, float p3FromY, float p4FromX, float p4FromY) throws NotFoundException { PerspectiveTransform transform = PerspectiveTransform.quadrilateralToQuadrilateral( p1ToX, p1ToY, p2ToX, p2ToY, p3ToX, p3ToY, p4ToX, p4ToY, p1FromX, p1FromY, p2FromX, p2FromY, p3FromX, p3FromY, p4FromX, p4FromY); return sampleGrid(image, dimensionX, dimensionY, transform); } @Override public BitMatrix sampleGrid(BitMatrix image, int dimensionX, int dimensionY, PerspectiveTransform transform) throws NotFoundException { if (dimensionX <= 0 || dimensionY <= 0) { throw NotFoundException.getNotFoundInstance(); } BitMatrix bits = new BitMatrix(dimensionX, dimensionY); float[] points = new float[dimensionX << 1]; for (int y = 0; y < dimensionY; y++) { int max = points.length; float iValue = (float) y + 0.5f; for (int x = 0; x < max; x += 2) { points[x] = (float) (x >> 1) + 0.5f; points[x + 1] = iValue; } transform.transformPoints(points); // Quick check to see if points transformed to something inside the image; // sufficient to check the endpoints checkAndNudgePoints(image, points); try { for (int x = 0; x < max; x += 2) { if (image.get((int) points[x], (int) points[x + 1])) { // Black(-ish) pixel bits.set(x >> 1, y); } } } catch (ArrayIndexOutOfBoundsException aioobe) { // This feels wrong, but, sometimes if the finder patterns are misidentified, the resulting // transform gets "twisted" such that it maps a straight line of points to a set of points // whose endpoints are in bounds, but others are not. There is probably some mathematical // way to detect this about the transformation that I don't know yet. // This results in an ugly runtime exception despite our clever checks above -- can't have // that. We could check each point's coordinates but that feels duplicative. We settle for // catching and wrapping ArrayIndexOutOfBoundsException. throw NotFoundException.getNotFoundInstance(); } } return bits; } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/common/DefaultGridSampler.java
Java
epl
3,615
/* * Copyright 2007 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.common; /** * <p>This class implements a perspective transform in two dimensions. Given four source and four * destination points, it will compute the transformation implied between them. The code is based * directly upon section 3.4.2 of George Wolberg's "Digital Image Warping"; see pages 54-56.</p> * * @author Sean Owen */ public final class PerspectiveTransform { private final float a11; private final float a12; private final float a13; private final float a21; private final float a22; private final float a23; private final float a31; private final float a32; private final float a33; private PerspectiveTransform(float a11, float a21, float a31, float a12, float a22, float a32, float a13, float a23, float a33) { this.a11 = a11; this.a12 = a12; this.a13 = a13; this.a21 = a21; this.a22 = a22; this.a23 = a23; this.a31 = a31; this.a32 = a32; this.a33 = a33; } public static PerspectiveTransform quadrilateralToQuadrilateral(float x0, float y0, float x1, float y1, float x2, float y2, float x3, float y3, float x0p, float y0p, float x1p, float y1p, float x2p, float y2p, float x3p, float y3p) { PerspectiveTransform qToS = quadrilateralToSquare(x0, y0, x1, y1, x2, y2, x3, y3); PerspectiveTransform sToQ = squareToQuadrilateral(x0p, y0p, x1p, y1p, x2p, y2p, x3p, y3p); return sToQ.times(qToS); } public void transformPoints(float[] points) { int max = points.length; float a11 = this.a11; float a12 = this.a12; float a13 = this.a13; float a21 = this.a21; float a22 = this.a22; float a23 = this.a23; float a31 = this.a31; float a32 = this.a32; float a33 = this.a33; for (int i = 0; i < max; i += 2) { float x = points[i]; float y = points[i + 1]; float denominator = a13 * x + a23 * y + a33; points[i] = (a11 * x + a21 * y + a31) / denominator; points[i + 1] = (a12 * x + a22 * y + a32) / denominator; } } /** Convenience method, not optimized for performance. */ public void transformPoints(float[] xValues, float[] yValues) { int n = xValues.length; for (int i = 0; i < n; i ++) { float x = xValues[i]; float y = yValues[i]; float denominator = a13 * x + a23 * y + a33; xValues[i] = (a11 * x + a21 * y + a31) / denominator; yValues[i] = (a12 * x + a22 * y + a32) / denominator; } } public static PerspectiveTransform squareToQuadrilateral(float x0, float y0, float x1, float y1, float x2, float y2, float x3, float y3) { float dx3 = x0 - x1 + x2 - x3; float dy3 = y0 - y1 + y2 - y3; if (dx3 == 0.0f && dy3 == 0.0f) { // Affine return new PerspectiveTransform(x1 - x0, x2 - x1, x0, y1 - y0, y2 - y1, y0, 0.0f, 0.0f, 1.0f); } else { float dx1 = x1 - x2; float dx2 = x3 - x2; float dy1 = y1 - y2; float dy2 = y3 - y2; float denominator = dx1 * dy2 - dx2 * dy1; float a13 = (dx3 * dy2 - dx2 * dy3) / denominator; float a23 = (dx1 * dy3 - dx3 * dy1) / denominator; return new PerspectiveTransform(x1 - x0 + a13 * x1, x3 - x0 + a23 * x3, x0, y1 - y0 + a13 * y1, y3 - y0 + a23 * y3, y0, a13, a23, 1.0f); } } public static PerspectiveTransform quadrilateralToSquare(float x0, float y0, float x1, float y1, float x2, float y2, float x3, float y3) { // Here, the adjoint serves as the inverse: return squareToQuadrilateral(x0, y0, x1, y1, x2, y2, x3, y3).buildAdjoint(); } PerspectiveTransform buildAdjoint() { // Adjoint is the transpose of the cofactor matrix: return new PerspectiveTransform(a22 * a33 - a23 * a32, a23 * a31 - a21 * a33, a21 * a32 - a22 * a31, a13 * a32 - a12 * a33, a11 * a33 - a13 * a31, a12 * a31 - a11 * a32, a12 * a23 - a13 * a22, a13 * a21 - a11 * a23, a11 * a22 - a12 * a21); } PerspectiveTransform times(PerspectiveTransform other) { return new PerspectiveTransform(a11 * other.a11 + a21 * other.a12 + a31 * other.a13, a11 * other.a21 + a21 * other.a22 + a31 * other.a23, a11 * other.a31 + a21 * other.a32 + a31 * other.a33, a12 * other.a11 + a22 * other.a12 + a32 * other.a13, a12 * other.a21 + a22 * other.a22 + a32 * other.a23, a12 * other.a31 + a22 * other.a32 + a32 * other.a33, a13 * other.a11 + a23 * other.a12 + a33 * other.a13, a13 * other.a21 + a23 * other.a22 + a33 * other.a23, a13 * other.a31 + a23 * other.a32 + a33 * other.a33); } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/common/PerspectiveTransform.java
Java
epl
6,390
/* * Copyright 2008 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.common; import com.google.zxing.FormatException; import java.util.HashMap; import java.util.Map; /** * Encapsulates a Character Set ECI, according to "Extended Channel Interpretations" 5.3.1.1 * of ISO 18004. * * @author Sean Owen */ public enum CharacterSetECI { // Enum name is a Java encoding valid for java.lang and java.io Cp437(new int[]{0,2}), ISO8859_1(new int[]{1,3}, "ISO-8859-1"), ISO8859_2(4, "ISO-8859-2"), ISO8859_3(5, "ISO-8859-3"), ISO8859_4(6, "ISO-8859-4"), ISO8859_5(7, "ISO-8859-5"), ISO8859_6(8, "ISO-8859-6"), ISO8859_7(9, "ISO-8859-7"), ISO8859_8(10, "ISO-8859-8"), ISO8859_9(11, "ISO-8859-9"), ISO8859_10(12, "ISO-8859-10"), ISO8859_11(13, "ISO-8859-11"), ISO8859_13(15, "ISO-8859-13"), ISO8859_14(16, "ISO-8859-14"), ISO8859_15(17, "ISO-8859-15"), ISO8859_16(18, "ISO-8859-16"), SJIS(20, "Shift_JIS"), Cp1250(21, "windows-1250"), Cp1251(22, "windows-1251"), Cp1252(23, "windows-1252"), Cp1256(24, "windows-1256"), UnicodeBigUnmarked(25, "UTF-16BE", "UnicodeBig"), UTF8(26, "UTF-8"), ASCII(new int[] {27, 170}, "US-ASCII"), Big5(28), GB18030(29, "GB2312", "EUC_CN", "GBK"), EUC_KR(30, "EUC-KR"); private static final Map<Integer,CharacterSetECI> VALUE_TO_ECI = new HashMap<Integer,CharacterSetECI>(); private static final Map<String,CharacterSetECI> NAME_TO_ECI = new HashMap<String,CharacterSetECI>(); static { for (CharacterSetECI eci : values()) { for (int value : eci.values) { VALUE_TO_ECI.put(value, eci); } NAME_TO_ECI.put(eci.name(), eci); for (String name : eci.otherEncodingNames) { NAME_TO_ECI.put(name, eci); } } } private final int[] values; private final String[] otherEncodingNames; CharacterSetECI(int value) { this(new int[] {value}); } CharacterSetECI(int value, String... otherEncodingNames) { this.values = new int[] {value}; this.otherEncodingNames = otherEncodingNames; } CharacterSetECI(int[] values, String... otherEncodingNames) { this.values = values; this.otherEncodingNames = otherEncodingNames; } public int getValue() { return values[0]; } /** * @param value character set ECI value * @return CharacterSetECI representing ECI of given value, or null if it is legal but * unsupported * @throws IllegalArgumentException if ECI value is invalid */ public static CharacterSetECI getCharacterSetECIByValue(int value) throws FormatException { if (value < 0 || value >= 900) { throw FormatException.getFormatInstance(); } return VALUE_TO_ECI.get(value); } /** * @param name character set ECI encoding name * @return CharacterSetECI representing ECI for character encoding, or null if it is legal * but unsupported */ public static CharacterSetECI getCharacterSetECIByName(String name) { return NAME_TO_ECI.get(name); } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/common/CharacterSetECI.java
Java
epl
3,539
/* * Copyright 2007 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.common; /** * <p>Represents a 2D matrix of bits. In function arguments below, and throughout the common * module, x is the column position, and y is the row position. The ordering is always x, y. * The origin is at the top-left.</p> * * <p>Internally the bits are represented in a 1-D array of 32-bit ints. However, each row begins * with a new int. This is done intentionally so that we can copy out a row into a BitArray very * efficiently.</p> * * <p>The ordering of bits is row-major. Within each int, the least significant bits are used first, * meaning they represent lower x values. This is compatible with BitArray's implementation.</p> * * @author Sean Owen * @author dswitkin@google.com (Daniel Switkin) */ public final class BitMatrix { private final int width; private final int height; private final int rowSize; private final int[] bits; // A helper to construct a square matrix. public BitMatrix(int dimension) { this(dimension, dimension); } public BitMatrix(int width, int height) { if (width < 1 || height < 1) { throw new IllegalArgumentException("Both dimensions must be greater than 0"); } this.width = width; this.height = height; this.rowSize = (width + 31) >> 5; bits = new int[rowSize * height]; } /** * <p>Gets the requested bit, where true means black.</p> * * @param x The horizontal component (i.e. which column) * @param y The vertical component (i.e. which row) * @return value of given bit in matrix */ public boolean get(int x, int y) { int offset = y * rowSize + (x >> 5); return ((bits[offset] >>> (x & 0x1f)) & 1) != 0; } /** * <p>Sets the given bit to true.</p> * * @param x The horizontal component (i.e. which column) * @param y The vertical component (i.e. which row) */ public void set(int x, int y) { int offset = y * rowSize + (x >> 5); bits[offset] |= 1 << (x & 0x1f); } /** * <p>Flips the given bit.</p> * * @param x The horizontal component (i.e. which column) * @param y The vertical component (i.e. which row) */ public void flip(int x, int y) { int offset = y * rowSize + (x >> 5); bits[offset] ^= 1 << (x & 0x1f); } /** * Clears all bits (sets to false). */ public void clear() { int max = bits.length; for (int i = 0; i < max; i++) { bits[i] = 0; } } /** * <p>Sets a square region of the bit matrix to true.</p> * * @param left The horizontal position to begin at (inclusive) * @param top The vertical position to begin at (inclusive) * @param width The width of the region * @param height The height of the region */ public void setRegion(int left, int top, int width, int height) { if (top < 0 || left < 0) { throw new IllegalArgumentException("Left and top must be nonnegative"); } if (height < 1 || width < 1) { throw new IllegalArgumentException("Height and width must be at least 1"); } int right = left + width; int bottom = top + height; if (bottom > this.height || right > this.width) { throw new IllegalArgumentException("The region must fit inside the matrix"); } for (int y = top; y < bottom; y++) { int offset = y * rowSize; for (int x = left; x < right; x++) { bits[offset + (x >> 5)] |= 1 << (x & 0x1f); } } } /** * A fast method to retrieve one row of data from the matrix as a BitArray. * * @param y The row to retrieve * @param row An optional caller-allocated BitArray, will be allocated if null or too small * @return The resulting BitArray - this reference should always be used even when passing * your own row */ public BitArray getRow(int y, BitArray row) { if (row == null || row.getSize() < width) { row = new BitArray(width); } int offset = y * rowSize; for (int x = 0; x < rowSize; x++) { row.setBulk(x << 5, bits[offset + x]); } return row; } /** * @param y row to set * @param row {@link BitArray} to copy from */ public void setRow(int y, BitArray row) { System.arraycopy(row.getBitArray(), 0, bits, y * rowSize, rowSize); } /** * This is useful in detecting the enclosing rectangle of a 'pure' barcode. * * @return {left,top,width,height} enclosing rectangle of all 1 bits, or null if it is all white */ public int[] getEnclosingRectangle() { int left = width; int top = height; int right = -1; int bottom = -1; for (int y = 0; y < height; y++) { for (int x32 = 0; x32 < rowSize; x32++) { int theBits = bits[y * rowSize + x32]; if (theBits != 0) { if (y < top) { top = y; } if (y > bottom) { bottom = y; } if (x32 * 32 < left) { int bit = 0; while ((theBits << (31 - bit)) == 0) { bit++; } if ((x32 * 32 + bit) < left) { left = x32 * 32 + bit; } } if (x32 * 32 + 31 > right) { int bit = 31; while ((theBits >>> bit) == 0) { bit--; } if ((x32 * 32 + bit) > right) { right = x32 * 32 + bit; } } } } } int width = right - left; int height = bottom - top; if (width < 0 || height < 0) { return null; } return new int[] {left, top, width, height}; } /** * This is useful in detecting a corner of a 'pure' barcode. * * @return {x,y} coordinate of top-left-most 1 bit, or null if it is all white */ public int[] getTopLeftOnBit() { int bitsOffset = 0; while (bitsOffset < bits.length && bits[bitsOffset] == 0) { bitsOffset++; } if (bitsOffset == bits.length) { return null; } int y = bitsOffset / rowSize; int x = (bitsOffset % rowSize) << 5; int theBits = bits[bitsOffset]; int bit = 0; while ((theBits << (31-bit)) == 0) { bit++; } x += bit; return new int[] {x, y}; } public int[] getBottomRightOnBit() { int bitsOffset = bits.length - 1; while (bitsOffset >= 0 && bits[bitsOffset] == 0) { bitsOffset--; } if (bitsOffset < 0) { return null; } int y = bitsOffset / rowSize; int x = (bitsOffset % rowSize) << 5; int theBits = bits[bitsOffset]; int bit = 31; while ((theBits >>> bit) == 0) { bit--; } x += bit; return new int[] {x, y}; } /** * @return The width of the matrix */ public int getWidth() { return width; } /** * @return The height of the matrix */ public int getHeight() { return height; } @Override public boolean equals(Object o) { if (!(o instanceof BitMatrix)) { return false; } BitMatrix other = (BitMatrix) o; if (width != other.width || height != other.height || rowSize != other.rowSize || bits.length != other.bits.length) { return false; } for (int i = 0; i < bits.length; i++) { if (bits[i] != other.bits[i]) { return false; } } return true; } @Override public int hashCode() { int hash = width; hash = 31 * hash + width; hash = 31 * hash + height; hash = 31 * hash + rowSize; for (int bit : bits) { hash = 31 * hash + bit; } return hash; } @Override public String toString() { StringBuilder result = new StringBuilder(height * (width + 1)); for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { result.append(get(x, y) ? "X " : " "); } result.append('\n'); } return result.toString(); } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/common/BitMatrix.java
Java
epl
8,700
/* * Copyright 2007 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.common; import com.google.zxing.NotFoundException; /** * Implementations of this class can, given locations of finder patterns for a QR code in an * image, sample the right points in the image to reconstruct the QR code, accounting for * perspective distortion. It is abstracted since it is relatively expensive and should be allowed * to take advantage of platform-specific optimized implementations, like Sun's Java Advanced * Imaging library, but which may not be available in other environments such as J2ME, and vice * versa. * * The implementation used can be controlled by calling {@link #setGridSampler(GridSampler)} * with an instance of a class which implements this interface. * * @author Sean Owen */ public abstract class GridSampler { private static GridSampler gridSampler = new DefaultGridSampler(); /** * Sets the implementation of GridSampler used by the library. One global * instance is stored, which may sound problematic. But, the implementation provided * ought to be appropriate for the entire platform, and all uses of this library * in the whole lifetime of the JVM. For instance, an Android activity can swap in * an implementation that takes advantage of native platform libraries. * * @param newGridSampler The platform-specific object to install. */ public static void setGridSampler(GridSampler newGridSampler) { gridSampler = newGridSampler; } /** * @return the current implementation of GridSampler */ public static GridSampler getInstance() { return gridSampler; } /** * Samples an image for a rectangular matrix of bits of the given dimension. * @param image image to sample * @param dimensionX width of {@link BitMatrix} to sample from image * @param dimensionY height of {@link BitMatrix} to sample from image * @return {@link BitMatrix} representing a grid of points sampled from the image within a region * defined by the "from" parameters * @throws NotFoundException if image can't be sampled, for example, if the transformation defined * by the given points is invalid or results in sampling outside the image boundaries */ public abstract BitMatrix sampleGrid(BitMatrix image, int dimensionX, int dimensionY, float p1ToX, float p1ToY, float p2ToX, float p2ToY, float p3ToX, float p3ToY, float p4ToX, float p4ToY, float p1FromX, float p1FromY, float p2FromX, float p2FromY, float p3FromX, float p3FromY, float p4FromX, float p4FromY) throws NotFoundException; public abstract BitMatrix sampleGrid(BitMatrix image, int dimensionX, int dimensionY, PerspectiveTransform transform) throws NotFoundException; /** * <p>Checks a set of points that have been transformed to sample points on an image against * the image's dimensions to see if the point are even within the image.</p> * * <p>This method will actually "nudge" the endpoints back onto the image if they are found to be * barely (less than 1 pixel) off the image. This accounts for imperfect detection of finder * patterns in an image where the QR Code runs all the way to the image border.</p> * * <p>For efficiency, the method will check points from either end of the line until one is found * to be within the image. Because the set of points are assumed to be linear, this is valid.</p> * * @param image image into which the points should map * @param points actual points in x1,y1,...,xn,yn form * @throws NotFoundException if an endpoint is lies outside the image boundaries */ protected static void checkAndNudgePoints(BitMatrix image, float[] points) throws NotFoundException { int width = image.getWidth(); int height = image.getHeight(); // Check and nudge points from start until we see some that are OK: boolean nudged = true; for (int offset = 0; offset < points.length && nudged; offset += 2) { int x = (int) points[offset]; int y = (int) points[offset + 1]; if (x < -1 || x > width || y < -1 || y > height) { throw NotFoundException.getNotFoundInstance(); } nudged = false; if (x == -1) { points[offset] = 0.0f; nudged = true; } else if (x == width) { points[offset] = width - 1; nudged = true; } if (y == -1) { points[offset + 1] = 0.0f; nudged = true; } else if (y == height) { points[offset + 1] = height - 1; nudged = true; } } // Check and nudge points from end: nudged = true; for (int offset = points.length - 2; offset >= 0 && nudged; offset -= 2) { int x = (int) points[offset]; int y = (int) points[offset + 1]; if (x < -1 || x > width || y < -1 || y > height) { throw NotFoundException.getNotFoundInstance(); } nudged = false; if (x == -1) { points[offset] = 0.0f; nudged = true; } else if (x == width) { points[offset] = width - 1; nudged = true; } if (y == -1) { points[offset + 1] = 0.0f; nudged = true; } else if (y == height) { points[offset + 1] = height - 1; nudged = true; } } } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/common/GridSampler.java
Java
epl
6,363
/* * Copyright 2009 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.common; import com.google.zxing.Binarizer; import com.google.zxing.LuminanceSource; import com.google.zxing.NotFoundException; /** * This class implements a local thresholding algorithm, which while slower than the * GlobalHistogramBinarizer, is fairly efficient for what it does. It is designed for * high frequency images of barcodes with black data on white backgrounds. For this application, * it does a much better job than a global blackpoint with severe shadows and gradients. * However it tends to produce artifacts on lower frequency images and is therefore not * a good general purpose binarizer for uses outside ZXing. * * This class extends GlobalHistogramBinarizer, using the older histogram approach for 1D readers, * and the newer local approach for 2D readers. 1D decoding using a per-row histogram is already * inherently local, and only fails for horizontal gradients. We can revisit that problem later, * but for now it was not a win to use local blocks for 1D. * * This Binarizer is the default for the unit tests and the recommended class for library users. * * @author dswitkin@google.com (Daniel Switkin) */ public final class HybridBinarizer extends GlobalHistogramBinarizer { // This class uses 5x5 blocks to compute local luminance, where each block is 8x8 pixels. // So this is the smallest dimension in each axis we can accept. private static final int BLOCK_SIZE_POWER = 3; private static final int BLOCK_SIZE = 1 << BLOCK_SIZE_POWER; // ...0100...00 private static final int BLOCK_SIZE_MASK = BLOCK_SIZE - 1; // ...0011...11 private static final int MINIMUM_DIMENSION = BLOCK_SIZE * 5; private static final int MIN_DYNAMIC_RANGE = 24; private BitMatrix matrix; public HybridBinarizer(LuminanceSource source) { super(source); } /** * Calculates the final BitMatrix once for all requests. This could be called once from the * constructor instead, but there are some advantages to doing it lazily, such as making * profiling easier, and not doing heavy lifting when callers don't expect it. */ @Override public BitMatrix getBlackMatrix() throws NotFoundException { if (matrix != null) { return matrix; } LuminanceSource source = getLuminanceSource(); int width = source.getWidth(); int height = source.getHeight(); if (width >= MINIMUM_DIMENSION && height >= MINIMUM_DIMENSION) { byte[] luminances = source.getMatrix(); int subWidth = width >> BLOCK_SIZE_POWER; if ((width & BLOCK_SIZE_MASK) != 0) { subWidth++; } int subHeight = height >> BLOCK_SIZE_POWER; if ((height & BLOCK_SIZE_MASK) != 0) { subHeight++; } int[][] blackPoints = calculateBlackPoints(luminances, subWidth, subHeight, width, height); BitMatrix newMatrix = new BitMatrix(width, height); calculateThresholdForBlock(luminances, subWidth, subHeight, width, height, blackPoints, newMatrix); matrix = newMatrix; } else { // If the image is too small, fall back to the global histogram approach. matrix = super.getBlackMatrix(); } return matrix; } @Override public Binarizer createBinarizer(LuminanceSource source) { return new HybridBinarizer(source); } /** * For each block in the image, calculate the average black point using a 5x5 grid * of the blocks around it. Also handles the corner cases (fractional blocks are computed based * on the last pixels in the row/column which are also used in the previous block). */ private static void calculateThresholdForBlock(byte[] luminances, int subWidth, int subHeight, int width, int height, int[][] blackPoints, BitMatrix matrix) { for (int y = 0; y < subHeight; y++) { int yoffset = y << BLOCK_SIZE_POWER; int maxYOffset = height - BLOCK_SIZE; if (yoffset > maxYOffset) { yoffset = maxYOffset; } for (int x = 0; x < subWidth; x++) { int xoffset = x << BLOCK_SIZE_POWER; int maxXOffset = width - BLOCK_SIZE; if (xoffset > maxXOffset) { xoffset = maxXOffset; } int left = cap(x, 2, subWidth - 3); int top = cap(y, 2, subHeight - 3); int sum = 0; for (int z = -2; z <= 2; z++) { int[] blackRow = blackPoints[top + z]; sum += blackRow[left - 2] + blackRow[left - 1] + blackRow[left] + blackRow[left + 1] + blackRow[left + 2]; } int average = sum / 25; thresholdBlock(luminances, xoffset, yoffset, average, width, matrix); } } } private static int cap(int value, int min, int max) { return value < min ? min : value > max ? max : value; } /** * Applies a single threshold to a block of pixels. */ private static void thresholdBlock(byte[] luminances, int xoffset, int yoffset, int threshold, int stride, BitMatrix matrix) { for (int y = 0, offset = yoffset * stride + xoffset; y < BLOCK_SIZE; y++, offset += stride) { for (int x = 0; x < BLOCK_SIZE; x++) { // Comparison needs to be <= so that black == 0 pixels are black even if the threshold is 0. if ((luminances[offset + x] & 0xFF) <= threshold) { matrix.set(xoffset + x, yoffset + y); } } } } /** * Calculates a single black point for each block of pixels and saves it away. * See the following thread for a discussion of this algorithm: * http://groups.google.com/group/zxing/browse_thread/thread/d06efa2c35a7ddc0 */ private static int[][] calculateBlackPoints(byte[] luminances, int subWidth, int subHeight, int width, int height) { int[][] blackPoints = new int[subHeight][subWidth]; for (int y = 0; y < subHeight; y++) { int yoffset = y << BLOCK_SIZE_POWER; int maxYOffset = height - BLOCK_SIZE; if (yoffset > maxYOffset) { yoffset = maxYOffset; } for (int x = 0; x < subWidth; x++) { int xoffset = x << BLOCK_SIZE_POWER; int maxXOffset = width - BLOCK_SIZE; if (xoffset > maxXOffset) { xoffset = maxXOffset; } int sum = 0; int min = 0xFF; int max = 0; for (int yy = 0, offset = yoffset * width + xoffset; yy < BLOCK_SIZE; yy++, offset += width) { for (int xx = 0; xx < BLOCK_SIZE; xx++) { int pixel = luminances[offset + xx] & 0xFF; sum += pixel; // still looking for good contrast if (pixel < min) { min = pixel; } if (pixel > max) { max = pixel; } } // short-circuit min/max tests once dynamic range is met if (max - min > MIN_DYNAMIC_RANGE) { // finish the rest of the rows quickly for (yy++, offset += width; yy < BLOCK_SIZE; yy++, offset += width) { for (int xx = 0; xx < BLOCK_SIZE; xx++) { sum += luminances[offset + xx] & 0xFF; } } } } // The default estimate is the average of the values in the block. int average = sum >> (BLOCK_SIZE_POWER * 2); if (max - min <= MIN_DYNAMIC_RANGE) { // If variation within the block is low, assume this is a block with only light or only // dark pixels. In that case we do not want to use the average, as it would divide this // low contrast area into black and white pixels, essentially creating data out of noise. // // The default assumption is that the block is light/background. Since no estimate for // the level of dark pixels exists locally, use half the min for the block. average = min >> 1; if (y > 0 && x > 0) { // Correct the "white background" assumption for blocks that have neighbors by comparing // the pixels in this block to the previously calculated black points. This is based on // the fact that dark barcode symbology is always surrounded by some amount of light // background for which reasonable black point estimates were made. The bp estimated at // the boundaries is used for the interior. // The (min < bp) is arbitrary but works better than other heuristics that were tried. int averageNeighborBlackPoint = (blackPoints[y - 1][x] + (2 * blackPoints[y][x - 1]) + blackPoints[y - 1][x - 1]) >> 2; if (min < averageNeighborBlackPoint) { average = averageNeighborBlackPoint; } } } blackPoints[y][x] = average; } } return blackPoints; } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/common/HybridBinarizer.java
Java
epl
9,947
/* * Copyright (C) 2010 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.common; import java.util.Map; import com.google.zxing.DecodeHintType; /** * Common string-related functions. * * @author Sean Owen * @author Alex Dupre */ public final class StringUtils { private static final String PLATFORM_DEFAULT_ENCODING = System.getProperty("file.encoding"); public static final String SHIFT_JIS = "SJIS"; public static final String GB2312 = "GB2312"; private static final String EUC_JP = "EUC_JP"; private static final String UTF8 = "UTF8"; private static final String ISO88591 = "ISO8859_1"; private static final boolean ASSUME_SHIFT_JIS = SHIFT_JIS.equalsIgnoreCase(PLATFORM_DEFAULT_ENCODING) || EUC_JP.equalsIgnoreCase(PLATFORM_DEFAULT_ENCODING); private StringUtils() {} /** * @param bytes bytes encoding a string, whose encoding should be guessed * @param hints decode hints if applicable * @return name of guessed encoding; at the moment will only guess one of: * {@link #SHIFT_JIS}, {@link #UTF8}, {@link #ISO88591}, or the platform * default encoding if none of these can possibly be correct */ public static String guessEncoding(byte[] bytes, Map<DecodeHintType,?> hints) { if (hints != null) { String characterSet = (String) hints.get(DecodeHintType.CHARACTER_SET); if (characterSet != null) { return characterSet; } } // For now, merely tries to distinguish ISO-8859-1, UTF-8 and Shift_JIS, // which should be by far the most common encodings. int length = bytes.length; boolean canBeISO88591 = true; boolean canBeShiftJIS = true; boolean canBeUTF8 = true; int utf8BytesLeft = 0; //int utf8LowChars = 0; int utf2BytesChars = 0; int utf3BytesChars = 0; int utf4BytesChars = 0; int sjisBytesLeft = 0; //int sjisLowChars = 0; int sjisKatakanaChars = 0; //int sjisDoubleBytesChars = 0; int sjisCurKatakanaWordLength = 0; int sjisCurDoubleBytesWordLength = 0; int sjisMaxKatakanaWordLength = 0; int sjisMaxDoubleBytesWordLength = 0; //int isoLowChars = 0; //int isoHighChars = 0; int isoHighOther = 0; boolean utf8bom = bytes.length > 3 && bytes[0] == (byte) 0xEF && bytes[1] == (byte) 0xBB && bytes[2] == (byte) 0xBF; for (int i = 0; i < length && (canBeISO88591 || canBeShiftJIS || canBeUTF8); i++) { int value = bytes[i] & 0xFF; // UTF-8 stuff if (canBeUTF8) { if (utf8BytesLeft > 0) { if ((value & 0x80) == 0) { canBeUTF8 = false; } else { utf8BytesLeft--; } } else if ((value & 0x80) != 0) { if ((value & 0x40) == 0) { canBeUTF8 = false; } else { utf8BytesLeft++; if ((value & 0x20) == 0) { utf2BytesChars++; } else { utf8BytesLeft++; if ((value & 0x10) == 0) { utf3BytesChars++; } else { utf8BytesLeft++; if ((value & 0x08) == 0) { utf4BytesChars++; } else { canBeUTF8 = false; } } } } } //else { //utf8LowChars++; //} } // ISO-8859-1 stuff if (canBeISO88591) { if (value > 0x7F && value < 0xA0) { canBeISO88591 = false; } else if (value > 0x9F) { if (value < 0xC0 || value == 0xD7 || value == 0xF7) { isoHighOther++; } //else { //isoHighChars++; //} } //else { //isoLowChars++; //} } // Shift_JIS stuff if (canBeShiftJIS) { if (sjisBytesLeft > 0) { if (value < 0x40 || value == 0x7F || value > 0xFC) { canBeShiftJIS = false; } else { sjisBytesLeft--; } } else if (value == 0x80 || value == 0xA0 || value > 0xEF) { canBeShiftJIS = false; } else if (value > 0xA0 && value < 0xE0) { sjisKatakanaChars++; sjisCurDoubleBytesWordLength = 0; sjisCurKatakanaWordLength++; if (sjisCurKatakanaWordLength > sjisMaxKatakanaWordLength) { sjisMaxKatakanaWordLength = sjisCurKatakanaWordLength; } } else if (value > 0x7F) { sjisBytesLeft++; //sjisDoubleBytesChars++; sjisCurKatakanaWordLength = 0; sjisCurDoubleBytesWordLength++; if (sjisCurDoubleBytesWordLength > sjisMaxDoubleBytesWordLength) { sjisMaxDoubleBytesWordLength = sjisCurDoubleBytesWordLength; } } else { //sjisLowChars++; sjisCurKatakanaWordLength = 0; sjisCurDoubleBytesWordLength = 0; } } } if (canBeUTF8 && utf8BytesLeft > 0) { canBeUTF8 = false; } if (canBeShiftJIS && sjisBytesLeft > 0) { canBeShiftJIS = false; } // Easy -- if there is BOM or at least 1 valid not-single byte character (and no evidence it can't be UTF-8), done if (canBeUTF8 && (utf8bom || utf2BytesChars + utf3BytesChars + utf4BytesChars > 0)) { return UTF8; } // Easy -- if assuming Shift_JIS or at least 3 valid consecutive not-ascii characters (and no evidence it can't be), done if (canBeShiftJIS && (ASSUME_SHIFT_JIS || sjisMaxKatakanaWordLength >= 3 || sjisMaxDoubleBytesWordLength >= 3)) { return SHIFT_JIS; } // Distinguishing Shift_JIS and ISO-8859-1 can be a little tough for short words. The crude heuristic is: // - If we saw // - only two consecutive katakana chars in the whole text, or // - at least 10% of bytes that could be "upper" not-alphanumeric Latin1, // - then we conclude Shift_JIS, else ISO-8859-1 if (canBeISO88591 && canBeShiftJIS) { return (sjisMaxKatakanaWordLength == 2 && sjisKatakanaChars == 2) || isoHighOther * 10 >= length ? SHIFT_JIS : ISO88591; } // Otherwise, try in order ISO-8859-1, Shift JIS, UTF-8 and fall back to default platform encoding if (canBeISO88591) { return ISO88591; } if (canBeShiftJIS) { return SHIFT_JIS; } if (canBeUTF8) { return UTF8; } // Otherwise, we take a wild guess with platform encoding return PLATFORM_DEFAULT_ENCODING; } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/common/StringUtils.java
Java
epl
7,018
/* * Copyright 2007 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.common; import com.google.zxing.ResultPoint; /** * <p>Encapsulates the result of detecting a barcode in an image. This includes the raw * matrix of black/white pixels corresponding to the barcode, and possibly points of interest * in the image, like the location of finder patterns or corners of the barcode in the image.</p> * * @author Sean Owen */ public class DetectorResult { private final BitMatrix bits; private final ResultPoint[] points; public DetectorResult(BitMatrix bits, ResultPoint[] points) { this.bits = bits; this.points = points; } public final BitMatrix getBits() { return bits; } public final ResultPoint[] getPoints() { return points; } }
zzdache
trunk/android/cc/CcCommon/sdk/com/google/zxing/common/DetectorResult.java
Java
epl
1,329