Search in sources :

Example 1 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 2 with ReaderException

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

the class BenchmarkAsyncTask method decode.

private static BenchmarkItem decode(MultiFormatReader reader, File file) {
    Bitmap imageBitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
    if (imageBitmap == null) {
        Log.e(TAG, "Couldn't open " + file);
        return null;
    }
    int width = imageBitmap.getWidth();
    int height = imageBitmap.getHeight();
    int[] pixels = new int[width * height];
    imageBitmap.getPixels(pixels, 0, width, 0, 0, width, height);
    RGBLuminanceSource source = new RGBLuminanceSource(width, height, pixels);
    BenchmarkItem item = new BenchmarkItem(file, RUNS);
    for (int x = 0; x < RUNS; x++) {
        boolean success;
        Result result = null;
        // Using this call instead of getting the time should eliminate a lot of variability due to
        // scheduling and what else is happening in the system.
        long now = Debug.threadCpuTimeNanos();
        try {
            BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
            result = reader.decodeWithState(bitmap);
            success = true;
        } catch (ReaderException ignored) {
            success = false;
        }
        now = Debug.threadCpuTimeNanos() - now;
        if (x == 0) {
            item.setDecoded(success);
            item.setFormat(result != null ? result.getBarcodeFormat() : null);
        }
        item.addResult((int) (now / 1000));
    }
    return item;
}
Also used : Bitmap(android.graphics.Bitmap) BinaryBitmap(com.google.zxing.BinaryBitmap) BinaryBitmap(com.google.zxing.BinaryBitmap) HybridBinarizer(com.google.zxing.common.HybridBinarizer) RGBLuminanceSource(com.google.zxing.RGBLuminanceSource) Result(com.google.zxing.Result) ReaderException(com.google.zxing.ReaderException)

Example 3 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)

Example 4 with ReaderException

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

the class AbstractNegativeBlackBoxTestCase method checkForFalsePositives.

/**
   * Make sure ZXing does NOT find a barcode in the image.
   *
   * @param image The image to test
   * @param rotationInDegrees The amount of rotation to apply
   * @return true if nothing found, false if a non-existent barcode was detected
   */
private boolean checkForFalsePositives(BufferedImage image, float rotationInDegrees) {
    BufferedImage rotatedImage = rotateImage(image, rotationInDegrees);
    LuminanceSource source = new BufferedImageLuminanceSource(rotatedImage);
    BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
    Result result;
    try {
        result = getReader().decode(bitmap);
        log.info(String.format("Found false positive: '%s' with format '%s' (rotation: %d)", result.getText(), result.getBarcodeFormat(), (int) rotationInDegrees));
        return false;
    } catch (ReaderException re) {
    // continue
    }
    // Try "try harder" getMode
    Map<DecodeHintType, Object> hints = new EnumMap<>(DecodeHintType.class);
    hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
    try {
        result = getReader().decode(bitmap, hints);
        log.info(String.format("Try harder found false positive: '%s' with format '%s' (rotation: %d)", result.getText(), result.getBarcodeFormat(), (int) rotationInDegrees));
        return false;
    } catch (ReaderException re) {
    // continue
    }
    return true;
}
Also used : LuminanceSource(com.google.zxing.LuminanceSource) BufferedImageLuminanceSource(com.google.zxing.BufferedImageLuminanceSource) DecodeHintType(com.google.zxing.DecodeHintType) BufferedImageLuminanceSource(com.google.zxing.BufferedImageLuminanceSource) BinaryBitmap(com.google.zxing.BinaryBitmap) EnumMap(java.util.EnumMap) BufferedImage(java.awt.image.BufferedImage) Result(com.google.zxing.Result) ReaderException(com.google.zxing.ReaderException)

Example 5 with ReaderException

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

the class RSSExpandedImage2binaryTestCase method assertCorrectImage2binary.

private static void assertCorrectImage2binary(String fileName, String expected) throws IOException, NotFoundException {
    Path path = AbstractBlackBoxTestCase.buildTestBase("src/test/resources/blackbox/rssexpanded-1/").resolve(fileName);
    BufferedImage image = ImageIO.read(path.toFile());
    BinaryBitmap binaryMap = new BinaryBitmap(new GlobalHistogramBinarizer(new BufferedImageLuminanceSource(image)));
    int rowNumber = binaryMap.getHeight() / 2;
    BitArray row = binaryMap.getBlackRow(rowNumber, null);
    List<ExpandedPair> pairs;
    try {
        RSSExpandedReader rssExpandedReader = new RSSExpandedReader();
        pairs = rssExpandedReader.decodeRow2pairs(rowNumber, row);
    } catch (ReaderException re) {
        fail(re.toString());
        return;
    }
    BitArray binary = BitArrayBuilder.buildBitArray(pairs);
    assertEquals(expected, binary.toString());
}
Also used : Path(java.nio.file.Path) GlobalHistogramBinarizer(com.google.zxing.common.GlobalHistogramBinarizer) BufferedImageLuminanceSource(com.google.zxing.BufferedImageLuminanceSource) BitArray(com.google.zxing.common.BitArray) BinaryBitmap(com.google.zxing.BinaryBitmap) BufferedImage(java.awt.image.BufferedImage) ReaderException(com.google.zxing.ReaderException)

Aggregations

ReaderException (com.google.zxing.ReaderException)64 Result (com.google.zxing.Result)58 BinaryBitmap (com.google.zxing.BinaryBitmap)39 HybridBinarizer (com.google.zxing.common.HybridBinarizer)34 Message (android.os.Message)25 Bundle (android.os.Bundle)24 ResultPoint (com.google.zxing.ResultPoint)16 PlanarYUVLuminanceSource (com.google.zxing.PlanarYUVLuminanceSource)15 Handler (android.os.Handler)14 ArrayList (java.util.ArrayList)10 BarcodeFormat (com.google.zxing.BarcodeFormat)8 ResultPointCallback (com.google.zxing.ResultPointCallback)8 DetectorResult (com.google.zxing.common.DetectorResult)8 BufferedImage (java.awt.image.BufferedImage)8 LuminanceSource (com.google.zxing.LuminanceSource)7 BitArray (com.google.zxing.common.BitArray)7 BufferedImageLuminanceSource (com.google.zxing.BufferedImageLuminanceSource)6 DecodeHintType (com.google.zxing.DecodeHintType)6 EnumMap (java.util.EnumMap)6 MultiFormatReader (com.google.zxing.MultiFormatReader)5