I'm using zxing to read barcodes from scanned images like this:
Ideally the barcode is always placed at 2/5 position but sometime the barcode is blurred, dirt or scratched, for testing purpose is required to save the bitmap sent to reader, based on this answer: Convert byte array of data type TYPE_4BYTE_ABGR to BufferedImage I'm trying to save the croppedBitmap without success, any help really appreciated.
private static String decodeFile(File file) throws IOException, NotFoundException {
BufferedImage bufferedImage = ImageIO.read(file);
LuminanceSource source = new
BufferedImageLuminanceSource(bufferedImage);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
System.out.println(bitmap.getWidth() + " x " + bitmap.getHeight());
int width = bitmap.getWidth();
int height = bitmap.getHeight() / 5;
int top = height;
BinaryBitmap croppedBitmap = bitmap.crop(0, top, width, height);
int[] dst = new int[width * height];
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
int a = croppedBitmap.getBlackMatrix().get(i, j) ? 1 & 0xff : 0;
int b = croppedBitmap.getBlackMatrix().get(i, j) ? 1 & 0xff : 0;
int g = croppedBitmap.getBlackMatrix().get(i, j) ? 1 & 0xff : 0;
int r = croppedBitmap.getBlackMatrix().get(i, j) ? 1 & 0xff : 0;
dst[(i + 1) * j] = (a << 24) | (r << 16) | (g << 8) | b;
}
}
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_ARGB);
image.setRGB(0, 0, width, height, dst, 0, width);
boolean r = ImageIO.write(image, "bmp", new File("croppedBitmap.bmp"));
System.out.println("Write bmp:" + r);
Hashtable<DecodeHintType, Object> hint = new Hashtable<DecodeHintType, Object>();
hint.put(DecodeHintType.TRY_HARDER, BarcodeFormat.CODE_39);
try {
MultiFormatReader reader = new MultiFormatReader();
Result result = reader.decode(bitmap, hint);
return result.getText();
} catch (NotFoundException e) {
System.out.println("Decode failed.");
return null;
}
}
Use toBufferedImage
:
BitMatrix blackMatrix = croppedBitmap.getBlackMatrix();
BufferedImage image = MatrixToImageWriter.toBufferedImage(blackMatrix);