Search in sources :

Example 6 with ReaderException

use of com.google.zxing.ReaderException in project weex-example by KalicyZhou.

the class DecodeHandler method decode.

/**
   * Decode the data within the viewfinder rectangle, and time how long it took. For efficiency,
   * reuse the same reader objects from one decode to the next.
   *
   * @param data   The YUV preview frame.
   * @param width  The width of the preview frame.
   * @param height The height of the preview frame.
   */
private void decode(byte[] data, int width, int height) {
    long start = System.currentTimeMillis();
    Result rawResult = null;
    //    PlanarYUVLuminanceSource source = activity.getCameraManager().buildLuminanceSource(data, width, height);
    byte[] rotatedData = new byte[data.length];
    for (int y = 0; y < height; y++) {
        for (int x = 0; x < width; x++) rotatedData[x * height + height - y - 1] = data[x + y * width];
    }
    int tmp = width;
    width = height;
    height = tmp;
    PlanarYUVLuminanceSource source = activity.getCameraManager().buildLuminanceSource(rotatedData, width, height);
    if (source != null) {
        BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
        try {
            rawResult = multiFormatReader.decodeWithState(bitmap);
        } catch (ReaderException re) {
        // continue
        } finally {
            multiFormatReader.reset();
        }
    }
    Handler handler = activity.getHandler();
    if (rawResult != null) {
        // Don't log the barcode contents for security.
        long end = System.currentTimeMillis();
        Log.d(TAG, "Found barcode in " + (end - start) + " ms");
        if (handler != null) {
            Message message = Message.obtain(handler, R.id.decode_succeeded, rawResult);
            Bundle bundle = new Bundle();
            bundleThumbnail(source, bundle);
            message.setData(bundle);
            message.sendToTarget();
        }
    } else {
        if (handler != null) {
            Message message = Message.obtain(handler, R.id.decode_failed);
            message.sendToTarget();
        }
    }
}
Also used : Message(android.os.Message) PlanarYUVLuminanceSource(com.google.zxing.PlanarYUVLuminanceSource) Bundle(android.os.Bundle) Handler(android.os.Handler) BinaryBitmap(com.google.zxing.BinaryBitmap) HybridBinarizer(com.google.zxing.common.HybridBinarizer) Result(com.google.zxing.Result) ReaderException(com.google.zxing.ReaderException)

Example 7 with ReaderException

use of com.google.zxing.ReaderException in project weex-example by KalicyZhou.

the class MultiFormatUPCEANReader method decodeRow.

@Override
public Result decodeRow(int rowNumber, BitArray row, Map<DecodeHintType, ?> hints) throws NotFoundException {
    // Compute this location once and reuse it on multiple implementations
    int[] startGuardPattern = UPCEANReader.findStartGuardPattern(row);
    for (UPCEANReader reader : readers) {
        Result result;
        try {
            result = reader.decodeRow(rowNumber, row, startGuardPattern, hints);
        } catch (ReaderException ignored) {
            continue;
        }
        // Special case: a 12-digit code encoded in UPC-A is identical to a "0"
        // followed by those 12 digits encoded as EAN-13. Each will recognize such a code,
        // UPC-A as a 12-digit string and EAN-13 as a 13-digit string starting with "0".
        // Individually these are correct and their readers will both read such a code
        // and correctly call it EAN-13, or UPC-A, respectively.
        //
        // In this case, if we've been looking for both types, we'd like to call it
        // a UPC-A code. But for efficiency we only run the EAN-13 decoder to also read
        // UPC-A. So we special case it here, and convert an EAN-13 result to a UPC-A
        // result if appropriate.
        //
        // But, don't return UPC-A if UPC-A was not a requested format!
        boolean ean13MayBeUPCA = result.getBarcodeFormat() == BarcodeFormat.EAN_13 && result.getText().charAt(0) == '0';
        @SuppressWarnings("unchecked") Collection<BarcodeFormat> possibleFormats = hints == null ? null : (Collection<BarcodeFormat>) hints.get(DecodeHintType.POSSIBLE_FORMATS);
        boolean canReturnUPCA = possibleFormats == null || possibleFormats.contains(BarcodeFormat.UPC_A);
        if (ean13MayBeUPCA && canReturnUPCA) {
            // Transfer the metdata across
            Result resultUPCA = new Result(result.getText().substring(1), result.getRawBytes(), result.getResultPoints(), BarcodeFormat.UPC_A);
            resultUPCA.putAllMetadata(result.getResultMetadata());
            return resultUPCA;
        }
        return result;
    }
    throw NotFoundException.getNotFoundInstance();
}
Also used : BarcodeFormat(com.google.zxing.BarcodeFormat) Result(com.google.zxing.Result) ReaderException(com.google.zxing.ReaderException)

Example 8 with ReaderException

use of com.google.zxing.ReaderException in project weex-example by KalicyZhou.

the class OneDReader method doDecode.

/**
   * 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) {
        // Look at the whole image, not just the center
        maxLines = height;
    } else {
        // 15 rows spaced 1/32 apart is roughly the middle half of the image
        maxLines = 15;
    }
    for (int x = 0; x < maxLines; x++) {
        // Scanning from the middle out. Determine which row we're looking at next:
        int rowStepsAboveOrBelow = (x + 1) / 2;
        // i.e. is x even?
        boolean isAbove = (x & 0x01) == 0;
        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;
        }
        // handle decoding upside down barcodes.
        for (int attempt = 0; attempt < 2; attempt++) {
            if (attempt == 1) {
                // trying again?
                // reverse the row and continue
                row.reverse();
                // that start on the center line.
                if (hints != null && hints.containsKey(DecodeHintType.NEED_RESULT_POINT_CALLBACK)) {
                    Map<DecodeHintType, Object> newHints = new EnumMap<>(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();
}
Also used : ResultPoint(com.google.zxing.ResultPoint) DecodeHintType(com.google.zxing.DecodeHintType) NotFoundException(com.google.zxing.NotFoundException) BitArray(com.google.zxing.common.BitArray) EnumMap(java.util.EnumMap) ResultPoint(com.google.zxing.ResultPoint) Result(com.google.zxing.Result) ReaderException(com.google.zxing.ReaderException)

Example 9 with ReaderException

use of com.google.zxing.ReaderException in project zxing by zxing.

the class DecodeServlet method processImage.

private static void processImage(BufferedImage image, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
    LuminanceSource source = new BufferedImageLuminanceSource(image);
    BinaryBitmap bitmap = new BinaryBitmap(new GlobalHistogramBinarizer(source));
    Collection<Result> results = new ArrayList<>(1);
    try {
        Reader reader = new MultiFormatReader();
        ReaderException savedException = null;
        try {
            // Look for multiple barcodes
            MultipleBarcodeReader multiReader = new GenericMultipleBarcodeReader(reader);
            Result[] theResults = multiReader.decodeMultiple(bitmap, HINTS);
            if (theResults != null) {
                results.addAll(Arrays.asList(theResults));
            }
        } catch (ReaderException re) {
            savedException = re;
        }
        if (results.isEmpty()) {
            try {
                // Look for pure barcode
                Result theResult = reader.decode(bitmap, HINTS_PURE);
                if (theResult != null) {
                    results.add(theResult);
                }
            } catch (ReaderException re) {
                savedException = re;
            }
        }
        if (results.isEmpty()) {
            try {
                // Look for normal barcode in photo
                Result theResult = reader.decode(bitmap, HINTS);
                if (theResult != null) {
                    results.add(theResult);
                }
            } catch (ReaderException re) {
                savedException = re;
            }
        }
        if (results.isEmpty()) {
            try {
                // Try again with other binarizer
                BinaryBitmap hybridBitmap = new BinaryBitmap(new HybridBinarizer(source));
                Result theResult = reader.decode(hybridBitmap, HINTS);
                if (theResult != null) {
                    results.add(theResult);
                }
            } catch (ReaderException re) {
                savedException = re;
            }
        }
        if (results.isEmpty()) {
            try {
                throw savedException == null ? NotFoundException.getNotFoundInstance() : savedException;
            } catch (FormatException | ChecksumException e) {
                log.info(e.toString());
                errorResponse(request, response, "format");
            } catch (ReaderException e) {
                // Including NotFoundException
                log.info(e.toString());
                errorResponse(request, response, "notfound");
            }
            return;
        }
    } catch (RuntimeException re) {
        // Call out unexpected errors in the log clearly
        log.log(Level.WARNING, "Unexpected exception from library", re);
        throw new ServletException(re);
    }
    String fullParameter = request.getParameter("full");
    boolean minimalOutput = fullParameter != null && !Boolean.parseBoolean(fullParameter);
    if (minimalOutput) {
        response.setContentType(MediaType.PLAIN_TEXT_UTF_8.toString());
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        try (Writer out = new OutputStreamWriter(response.getOutputStream(), StandardCharsets.UTF_8)) {
            for (Result result : results) {
                out.write(result.getText());
                out.write('\n');
            }
        }
    } else {
        request.setAttribute("results", results);
        request.getRequestDispatcher("decoderesult.jspx").forward(request, response);
    }
}
Also used : GlobalHistogramBinarizer(com.google.zxing.common.GlobalHistogramBinarizer) MultiFormatReader(com.google.zxing.MultiFormatReader) GenericMultipleBarcodeReader(com.google.zxing.multi.GenericMultipleBarcodeReader) ChecksumException(com.google.zxing.ChecksumException) ArrayList(java.util.ArrayList) GenericMultipleBarcodeReader(com.google.zxing.multi.GenericMultipleBarcodeReader) MultipleBarcodeReader(com.google.zxing.multi.MultipleBarcodeReader) ImageReader(com.google.zxing.client.j2se.ImageReader) MultiFormatReader(com.google.zxing.MultiFormatReader) Reader(com.google.zxing.Reader) GenericMultipleBarcodeReader(com.google.zxing.multi.GenericMultipleBarcodeReader) MultipleBarcodeReader(com.google.zxing.multi.MultipleBarcodeReader) HybridBinarizer(com.google.zxing.common.HybridBinarizer) FormatException(com.google.zxing.FormatException) Result(com.google.zxing.Result) ReaderException(com.google.zxing.ReaderException) ServletException(javax.servlet.ServletException) LuminanceSource(com.google.zxing.LuminanceSource) BufferedImageLuminanceSource(com.google.zxing.client.j2se.BufferedImageLuminanceSource) BufferedImageLuminanceSource(com.google.zxing.client.j2se.BufferedImageLuminanceSource) OutputStreamWriter(java.io.OutputStreamWriter) BinaryBitmap(com.google.zxing.BinaryBitmap) Writer(java.io.Writer) OutputStreamWriter(java.io.OutputStreamWriter)

Example 10 with ReaderException

use of com.google.zxing.ReaderException in project zxing by zxing.

the class AbstractBlackBoxTestCase method decode.

private boolean decode(BinaryBitmap source, float rotation, String expectedText, Map<?, ?> expectedMetadata, boolean tryHarder) throws ReaderException {
    String suffix = String.format(" (%srotation: %d)", tryHarder ? "try harder, " : "", (int) rotation);
    Map<DecodeHintType, Object> hints = new EnumMap<>(DecodeHintType.class);
    if (tryHarder) {
        hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
    }
    // Try in 'pure' mode mostly to exercise PURE_BARCODE code paths for exceptions;
    // not expected to pass, generally
    Result result = null;
    try {
        Map<DecodeHintType, Object> pureHints = new EnumMap<>(hints);
        pureHints.put(DecodeHintType.PURE_BARCODE, Boolean.TRUE);
        result = barcodeReader.decode(source, pureHints);
    } catch (ReaderException re) {
    // continue
    }
    if (result == null) {
        result = barcodeReader.decode(source, hints);
    }
    if (expectedFormat != result.getBarcodeFormat()) {
        log.info(String.format("Format mismatch: expected '%s' but got '%s'%s", expectedFormat, result.getBarcodeFormat(), suffix));
        return false;
    }
    String resultText = result.getText();
    if (!expectedText.equals(resultText)) {
        log.info(String.format("Content mismatch: expected '%s' but got '%s'%s", expectedText, resultText, suffix));
        return false;
    }
    Map<ResultMetadataType, ?> resultMetadata = result.getResultMetadata();
    for (Map.Entry<?, ?> metadatum : expectedMetadata.entrySet()) {
        ResultMetadataType key = ResultMetadataType.valueOf(metadatum.getKey().toString());
        Object expectedValue = metadatum.getValue();
        Object actualValue = resultMetadata == null ? null : resultMetadata.get(key);
        if (!expectedValue.equals(actualValue)) {
            log.info(String.format("Metadata mismatch for key '%s': expected '%s' but got '%s'", key, expectedValue, actualValue));
            return false;
        }
    }
    return true;
}
Also used : DecodeHintType(com.google.zxing.DecodeHintType) ResultMetadataType(com.google.zxing.ResultMetadataType) EnumMap(java.util.EnumMap) Map(java.util.Map) EnumMap(java.util.EnumMap) Result(com.google.zxing.Result) ReaderException(com.google.zxing.ReaderException)

Aggregations

ReaderException (com.google.zxing.ReaderException)39 Result (com.google.zxing.Result)35 BinaryBitmap (com.google.zxing.BinaryBitmap)26 HybridBinarizer (com.google.zxing.common.HybridBinarizer)21 Bundle (android.os.Bundle)13 Message (android.os.Message)13 PlanarYUVLuminanceSource (com.google.zxing.PlanarYUVLuminanceSource)9 Handler (android.os.Handler)8 ResultPoint (com.google.zxing.ResultPoint)8 BufferedImage (java.awt.image.BufferedImage)7 BufferedImageLuminanceSource (com.google.zxing.BufferedImageLuminanceSource)6 ArrayList (java.util.ArrayList)6 LuminanceSource (com.google.zxing.LuminanceSource)5 MultiFormatReader (com.google.zxing.MultiFormatReader)5 BitArray (com.google.zxing.common.BitArray)5 Path (java.nio.file.Path)5 BarcodeFormat (com.google.zxing.BarcodeFormat)4 DecodeHintType (com.google.zxing.DecodeHintType)4 ResultPointCallback (com.google.zxing.ResultPointCallback)4 DetectorResult (com.google.zxing.common.DetectorResult)4