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);
}
}
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;
}
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;
}
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;
}
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());
}
Aggregations