com.google.zxing.FormatException Java Examples

The following examples show how to use com.google.zxing.FormatException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DecodedBitStreamParser.java    From ScreenCapture with MIT License 6 votes vote down vote up
private static int parseECIValue(BitSource bits) throws FormatException {
  int firstByte = bits.readBits(8);
  if ((firstByte & 0x80) == 0) {
    // just one byte
    return firstByte & 0x7F;
  }
  if ((firstByte & 0xC0) == 0x80) {
    // two bytes
    int secondByte = bits.readBits(8);
    return ((firstByte & 0x3F) << 8) | secondByte;
  }
  if ((firstByte & 0xE0) == 0xC0) {
    // three bytes
    int secondThirdBytes = bits.readBits(16);
    return ((firstByte & 0x1F) << 16) | secondThirdBytes;
  }
  throw FormatException.getFormatInstance();
}
 
Example #2
Source File: RSSExpandedReader.java    From Tesseract-OCR-Scanner with Apache License 2.0 6 votes vote down vote up
static Result constructResult(List<ExpandedPair> pairs) throws NotFoundException, FormatException {
  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
    );
}
 
Example #3
Source File: DecodedBitStreamParser.java    From Tesseract-OCR-Scanner with Apache License 2.0 6 votes vote down vote up
private static int parseECIValue(BitSource bits) throws FormatException {
  int firstByte = bits.readBits(8);
  if ((firstByte & 0x80) == 0) {
    // just one byte
    return firstByte & 0x7F;
  }
  if ((firstByte & 0xC0) == 0x80) {
    // two bytes
    int secondByte = bits.readBits(8);
    return ((firstByte & 0x3F) << 8) | secondByte;
  }
  if ((firstByte & 0xE0) == 0xC0) {
    // three bytes
    int secondThirdBytes = bits.readBits(16);
    return ((firstByte & 0x1F) << 16) | secondThirdBytes;
  }
  throw FormatException.getFormatInstance();
}
 
Example #4
Source File: AI01392xDecoder.java    From ScreenCapture with MIT License 6 votes vote down vote up
@Override
public String parseInformation() throws NotFoundException, FormatException {
  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();
}
 
Example #5
Source File: GeneralAppIdDecoder.java    From ScreenCapture with MIT License 6 votes vote down vote up
private BlockParsedResult parseIsoIec646Block() throws FormatException {
  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);
}
 
Example #6
Source File: GeneralAppIdDecoder.java    From ScreenCapture with MIT License 6 votes vote down vote up
private DecodedInformation parseBlocks() throws FormatException {
  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();
}
 
Example #7
Source File: GeneralAppIdDecoder.java    From Tesseract-OCR-Scanner with Apache License 2.0 6 votes vote down vote up
private BlockParsedResult parseIsoIec646Block() throws FormatException {
  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);
}
 
Example #8
Source File: GeneralAppIdDecoder.java    From ScreenCapture with MIT License 6 votes vote down vote up
String decodeAllCodes(StringBuilder buff, int initialPosition) throws NotFoundException, FormatException {
  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();
}
 
Example #9
Source File: RSSExpandedReader.java    From ScreenCapture with MIT License 6 votes vote down vote up
static Result constructResult(List<ExpandedPair> pairs) throws NotFoundException, FormatException {
  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
    );
}
 
Example #10
Source File: RSSExpandedReader.java    From ScreenCapture with MIT License 6 votes vote down vote up
@Override
public Result decodeRow(int rowNumber,
                        BitArray row,
                        Map<DecodeHintType,?> hints) throws NotFoundException, FormatException {
  // 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 {
    return constructResult(decodeRow2pairs(rowNumber, row));
  } catch (NotFoundException e) {
    // OK
  }

  this.pairs.clear();
  this.startFromEven = true;
  return constructResult(decodeRow2pairs(rowNumber, row));
}
 
Example #11
Source File: DecodedBitStreamParser.java    From ScreenCapture with MIT License 5 votes vote down vote up
/**
 * See specification GBT 18284-2000
 */
private static void decodeHanziSegment(BitSource bits,
                                       StringBuilder result,
                                       int count) throws FormatException {
  // Don't crash trying to read more bits than we have available.
  if (count * 13 > bits.available()) {
    throw FormatException.getFormatInstance();
  }

  // Each character will require 2 bytes. Read the characters as 2-byte pairs
  // and decode as GB2312 afterwards
  byte[] buffer = new byte[2 * count];
  int offset = 0;
  while (count > 0) {
    // Each 13 bits encodes a 2-byte character
    int twoBytes = bits.readBits(13);
    int assembledTwoBytes = ((twoBytes / 0x060) << 8) | (twoBytes % 0x060);
    if (assembledTwoBytes < 0x003BF) {
      // In the 0xA1A1 to 0xAAFE range
      assembledTwoBytes += 0x0A1A1;
    } else {
      // In the 0xB0A1 to 0xFAFE range
      assembledTwoBytes += 0x0A6A1;
    }
    buffer[offset] = (byte) ((assembledTwoBytes >> 8) & 0xFF);
    buffer[offset + 1] = (byte) (assembledTwoBytes & 0xFF);
    offset += 2;
    count--;
  }

  try {
    result.append(new String(buffer, StringUtils.GB2312));
  } catch (UnsupportedEncodingException ignored) {
    throw FormatException.getFormatInstance();
  }
}
 
Example #12
Source File: DecodedBitStreamParser.java    From Tesseract-OCR-Scanner with Apache License 2.0 5 votes vote down vote up
/**
 * See specification GBT 18284-2000
 */
private static void decodeHanziSegment(BitSource bits,
                                       StringBuilder result,
                                       int count) throws FormatException {
  // Don't crash trying to read more bits than we have available.
  if (count * 13 > bits.available()) {
    throw FormatException.getFormatInstance();
  }

  // Each character will require 2 bytes. Read the characters as 2-byte pairs
  // and decode as GB2312 afterwards
  byte[] buffer = new byte[2 * count];
  int offset = 0;
  while (count > 0) {
    // Each 13 bits encodes a 2-byte character
    int twoBytes = bits.readBits(13);
    int assembledTwoBytes = ((twoBytes / 0x060) << 8) | (twoBytes % 0x060);
    if (assembledTwoBytes < 0x003BF) {
      // In the 0xA1A1 to 0xAAFE range
      assembledTwoBytes += 0x0A1A1;
    } else {
      // In the 0xB0A1 to 0xFAFE range
      assembledTwoBytes += 0x0A6A1;
    }
    buffer[offset] = (byte) ((assembledTwoBytes >> 8) & 0xFF);
    buffer[offset + 1] = (byte) (assembledTwoBytes & 0xFF);
    offset += 2;
    count--;
  }

  try {
    result.append(new String(buffer, StringUtils.GB2312));
  } catch (UnsupportedEncodingException ignored) {
    throw FormatException.getFormatInstance();
  }
}
 
Example #13
Source File: DecodedBitStreamParser.java    From Tesseract-OCR-Scanner with Apache License 2.0 5 votes vote down vote up
private static void decodeKanjiSegment(BitSource bits,
                                       StringBuilder result,
                                       int count) throws FormatException {
  // Don't crash trying to read more bits than we have available.
  if (count * 13 > bits.available()) {
    throw FormatException.getFormatInstance();
  }

  // Each character will require 2 bytes. Read the characters as 2-byte pairs
  // and decode as Shift_JIS afterwards
  byte[] buffer = new byte[2 * count];
  int offset = 0;
  while (count > 0) {
    // Each 13 bits encodes a 2-byte character
    int twoBytes = bits.readBits(13);
    int assembledTwoBytes = ((twoBytes / 0x0C0) << 8) | (twoBytes % 0x0C0);
    if (assembledTwoBytes < 0x01F00) {
      // In the 0x8140 to 0x9FFC range
      assembledTwoBytes += 0x08140;
    } else {
      // In the 0xE040 to 0xEBBF range
      assembledTwoBytes += 0x0C140;
    }
    buffer[offset] = (byte) (assembledTwoBytes >> 8);
    buffer[offset + 1] = (byte) assembledTwoBytes;
    offset += 2;
    count--;
  }
  // Shift_JIS may not be supported in some environments:
  try {
    result.append(new String(buffer, StringUtils.SHIFT_JIS));
  } catch (UnsupportedEncodingException ignored) {
    throw FormatException.getFormatInstance();
  }
}
 
Example #14
Source File: UPCAReader.java    From Tesseract-OCR-Scanner with Apache License 2.0 5 votes vote down vote up
@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));
}
 
Example #15
Source File: AI01393xDecoder.java    From Tesseract-OCR-Scanner with Apache License 2.0 5 votes vote down vote up
@Override
public String parseInformation() throws NotFoundException, FormatException {
  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();
}
 
Example #16
Source File: QRCodeReader.java    From ScreenCapture with MIT License 5 votes vote down vote up
@Override
public final 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, hints);
    points = NO_POINTS;
  } else {
    DetectorResult detectorResult = new Detector(image.getBlackMatrix()).detect(hints);
    decoderResult = decoder.decode(detectorResult.getBits(), hints);
    points = detectorResult.getPoints();
  }

  // If the code was mirrored: swap the bottom-left and the top-right points.
  if (decoderResult.getOther() instanceof QRCodeDecoderMetaData) {
    ((QRCodeDecoderMetaData) decoderResult.getOther()).applyMirroredCorrection(points);
  }

  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);
  }
  if (decoderResult.hasStructuredAppend()) {
    result.putMetadata(ResultMetadataType.STRUCTURED_APPEND_SEQUENCE,
                       decoderResult.getStructuredAppendSequenceNumber());
    result.putMetadata(ResultMetadataType.STRUCTURED_APPEND_PARITY,
                       decoderResult.getStructuredAppendParity());
  }
  return result;
}
 
Example #17
Source File: BitMatrixParser.java    From Tesseract-OCR-Scanner with Apache License 2.0 5 votes vote down vote up
/**
 * <p>Reads format information from one of its two locations within the QR Code.</p>
 *
 * @return {@link FormatInformation} encapsulating the QR Code's format info
 * @throws FormatException if both format information locations cannot be parsed as
 * the valid encoding of format information
 */
FormatInformation readFormatInformation() throws FormatException {

  if (parsedFormatInfo != null) {
    return parsedFormatInfo;
  }

  // Read top-left format info bits
  int formatInfoBits1 = 0;
  for (int i = 0; i < 6; i++) {
    formatInfoBits1 = copyBit(i, 8, formatInfoBits1);
  }
  // .. and skip a bit in the timing pattern ...
  formatInfoBits1 = copyBit(7, 8, formatInfoBits1);
  formatInfoBits1 = copyBit(8, 8, formatInfoBits1);
  formatInfoBits1 = copyBit(8, 7, formatInfoBits1);
  // .. and skip a bit in the timing pattern ...
  for (int j = 5; j >= 0; j--) {
    formatInfoBits1 = copyBit(8, j, formatInfoBits1);
  }

  // Read the top-right/bottom-left pattern too
  int dimension = bitMatrix.getHeight();
  int formatInfoBits2 = 0;
  int jMin = dimension - 7;
  for (int j = dimension - 1; j >= jMin; j--) {
    formatInfoBits2 = copyBit(8, j, formatInfoBits2);
  }
  for (int i = dimension - 8; i < dimension; i++) {
    formatInfoBits2 = copyBit(i, 8, formatInfoBits2);
  }

  parsedFormatInfo = FormatInformation.decodeFormatInformation(formatInfoBits1, formatInfoBits2);
  if (parsedFormatInfo != null) {
    return parsedFormatInfo;
  }
  throw FormatException.getFormatInstance();
}
 
Example #18
Source File: OneDReader.java    From Tesseract-OCR-Scanner with Apache License 2.0 5 votes vote down vote up
@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;
    }
  }
}
 
Example #19
Source File: DecodedBitStreamParser.java    From ScreenCapture with MIT License 5 votes vote down vote up
private static void decodeKanjiSegment(BitSource bits,
                                       StringBuilder result,
                                       int count) throws FormatException {
  // Don't crash trying to read more bits than we have available.
  if (count * 13 > bits.available()) {
    throw FormatException.getFormatInstance();
  }

  // Each character will require 2 bytes. Read the characters as 2-byte pairs
  // and decode as Shift_JIS afterwards
  byte[] buffer = new byte[2 * count];
  int offset = 0;
  while (count > 0) {
    // Each 13 bits encodes a 2-byte character
    int twoBytes = bits.readBits(13);
    int assembledTwoBytes = ((twoBytes / 0x0C0) << 8) | (twoBytes % 0x0C0);
    if (assembledTwoBytes < 0x01F00) {
      // In the 0x8140 to 0x9FFC range
      assembledTwoBytes += 0x08140;
    } else {
      // In the 0xE040 to 0xEBBF range
      assembledTwoBytes += 0x0C140;
    }
    buffer[offset] = (byte) (assembledTwoBytes >> 8);
    buffer[offset + 1] = (byte) assembledTwoBytes;
    offset += 2;
    count--;
  }
  // Shift_JIS may not be supported in some environments:
  try {
    result.append(new String(buffer, StringUtils.SHIFT_JIS));
  } catch (UnsupportedEncodingException ignored) {
    throw FormatException.getFormatInstance();
  }
}
 
Example #20
Source File: BitMatrixParser.java    From Tesseract-OCR-Scanner with Apache License 2.0 5 votes vote down vote up
/**
 * @param bitMatrix {@link BitMatrix} to parse
 * @throws FormatException if dimension is not >= 21 and 1 mod 4
 */
BitMatrixParser(BitMatrix bitMatrix) throws FormatException {
  int dimension = bitMatrix.getHeight();
  if (dimension < 21 || (dimension & 0x03) != 1) {
    throw FormatException.getFormatInstance();
  }
  this.bitMatrix = bitMatrix;
}
 
Example #21
Source File: UPCAReader.java    From ScreenCapture with MIT License 5 votes vote down vote up
@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));
}
 
Example #22
Source File: QRCodeReader.java    From Tesseract-OCR-Scanner with Apache License 2.0 5 votes vote down vote up
@Override
public final 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, hints);
    points = NO_POINTS;
  } else {
    DetectorResult detectorResult = new Detector(image.getBlackMatrix()).detect(hints);
    decoderResult = decoder.decode(detectorResult.getBits(), hints);
    points = detectorResult.getPoints();
  }

  // If the code was mirrored: swap the bottom-left and the top-right points.
  if (decoderResult.getOther() instanceof QRCodeDecoderMetaData) {
    ((QRCodeDecoderMetaData) decoderResult.getOther()).applyMirroredCorrection(points);
  }

  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);
  }
  if (decoderResult.hasStructuredAppend()) {
    result.putMetadata(ResultMetadataType.STRUCTURED_APPEND_SEQUENCE,
                       decoderResult.getStructuredAppendSequenceNumber());
    result.putMetadata(ResultMetadataType.STRUCTURED_APPEND_PARITY,
                       decoderResult.getStructuredAppendParity());
  }
  return result;
}
 
Example #23
Source File: DecodedBitStreamParser.java    From Tesseract-OCR-Scanner with Apache License 2.0 5 votes vote down vote up
private static void decodeAlphanumericSegment(BitSource bits,
                                              StringBuilder result,
                                              int count,
                                              boolean fc1InEffect) throws FormatException {
  // Read two characters at a time
  int start = result.length();
  while (count > 1) {
    if (bits.available() < 11) {
      throw FormatException.getFormatInstance();
    }
    int nextTwoCharsBits = bits.readBits(11);
    result.append(toAlphaNumericChar(nextTwoCharsBits / 45));
    result.append(toAlphaNumericChar(nextTwoCharsBits % 45));
    count -= 2;
  }
  if (count == 1) {
    // special case: one character left
    if (bits.available() < 6) {
      throw FormatException.getFormatInstance();
    }
    result.append(toAlphaNumericChar(bits.readBits(6)));
  }
  // See section 6.4.8.1, 6.4.8.2
  if (fc1InEffect) {
    // We need to massage the result a bit if in an FNC1 mode:
    for (int i = start; i < result.length(); i++) {
      if (result.charAt(i) == '%') {
        if (i < result.length() - 1 && result.charAt(i + 1) == '%') {
          // %% is rendered as %
          result.deleteCharAt(i + 1);
        } else {
          // In alpha mode, % should be converted to FNC1 separator 0x1D
          result.setCharAt(i, (char) 0x1D);
        }
      }
    }
  }
}
 
Example #24
Source File: Detector.java    From Tesseract-OCR-Scanner with Apache License 2.0 5 votes vote down vote up
/**
 * <p>Detects a QR Code in an image.</p>
 *
 * @param hints optional hints to detector
 * @return {@link DetectorResult} encapsulating results of detecting a QR Code
 * @throws NotFoundException if QR Code cannot be found
 * @throws FormatException if a QR Code cannot be decoded
 */
public final DetectorResult detect(Map<DecodeHintType,?> hints) throws NotFoundException, FormatException {

  resultPointCallback = hints == null ? null :
      (ResultPointCallback) hints.get(DecodeHintType.NEED_RESULT_POINT_CALLBACK);

  FinderPatternFinder finder = new FinderPatternFinder(image, resultPointCallback);
  FinderPatternInfo info = finder.find(hints);

  return processFinderPatternInfo(info);
}
 
Example #25
Source File: GeneralAppIdDecoder.java    From ScreenCapture with MIT License 5 votes vote down vote up
DecodedInformation decodeGeneralPurposeField(int pos, String remaining) throws FormatException {
  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());
}
 
Example #26
Source File: AI01393xDecoder.java    From ScreenCapture with MIT License 5 votes vote down vote up
@Override
public String parseInformation() throws NotFoundException, FormatException {
  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();
}
 
Example #27
Source File: DecodedNumeric.java    From ScreenCapture with MIT License 5 votes vote down vote up
DecodedNumeric(int newPosition, int firstDigit, int secondDigit) throws FormatException {
  super(newPosition);

  if (firstDigit < 0 || firstDigit > 10 || secondDigit < 0 || secondDigit > 10) {
    throw FormatException.getFormatInstance();
  }

  this.firstDigit  = firstDigit;
  this.secondDigit = secondDigit;
}
 
Example #28
Source File: AI01AndOtherAIs.java    From ScreenCapture with MIT License 5 votes vote down vote up
@Override
public String parseInformation() throws NotFoundException, FormatException {
  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);
}
 
Example #29
Source File: UPCEANReader.java    From ScreenCapture with MIT License 5 votes vote down vote up
/**
 * 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 check = Character.digit(s.charAt(length - 1), 10);
  return getStandardUPCEANChecksum(s.subSequence(0, length - 1)) == check;
}
 
Example #30
Source File: OneDReader.java    From ScreenCapture with MIT License 5 votes vote down vote up
@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;
    }
  }
}