Last active
May 11, 2017 08:58
-
-
Save benjohnde/2cb3f86b216c46e472033bd6dd13c438 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class BarcodeScannerZXing implements BarcodeScannerService { | |
// RGBLuminanceSource of ZXing approximates luminance for faster barcode detection but can | |
// yield to different results in comparison with a Bitmap representation of the image | |
private void populateYUVLuminanceFromRGB(int[] rgb, byte[] yuv420sp, int width, int height) { | |
for (int i = 0; i < width * height; i++) { | |
float red = (rgb[i] >> 16) & 0xff; | |
float green = (rgb[i] >> 8) & 0xff; | |
float blue = (rgb[i]) & 0xff; | |
int luminance = (int) ((0.257f * red) + (0.504f * green) + (0.098f * blue) + 16); | |
yuv420sp[i] = (byte) (0xff & luminance); | |
} | |
} | |
public Result getBarcodeFromBitmap(Bitmap bitmap) { | |
int w = bitmap.getWidth(); | |
int h = bitmap.getHeight(); | |
int[] pixels = new int[w * h]; | |
byte[] yuv = new byte[w * h]; | |
bitmap.getPixels(pixels, 0, w, 0, 0, w, h); | |
populateYUVLuminanceFromRGB(pixels, yuv, w, h); | |
PlanarYUVLuminanceSource source = new PlanarYUVLuminanceSource(yuv, w, h, 0, 0, w, h, false); | |
Result rawResult = null; | |
BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(source)); | |
try { | |
rawResult = mMultiFormatReader.decodeWithState(binaryBitmap); | |
} catch (ReaderException | NullPointerException | ArrayIndexOutOfBoundsException re) { | |
// continue | |
} finally { | |
mMultiFormatReader.reset(); | |
} | |
if (rawResult == null) return null; | |
return rawResult; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment