Created
June 12, 2018 10:09
-
-
Save Tougee/d8e8caf700ce0fcbc9f3ddf42984519d to your computer and use it in GitHub Desktop.
Zxing Android decode QR code
This file contains 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
fun Bitmap.decodeQR(): String? { | |
val width = width | |
val height = height | |
val pixels = IntArray(width * height) | |
getPixels(pixels, 0, width, 0, 0, width, height) | |
val source = RGBLuminanceSource(width, height, pixels) | |
val binaryBitmap = BinaryBitmap(GlobalHistogramBinarizer(source)) | |
val reader = MultiFormatReader() | |
val hints = EnumMap<DecodeHintType, Any>(DecodeHintType::class.java) | |
hints[DecodeHintType.TRY_HARDER] = true | |
hints[DecodeHintType.POSSIBLE_FORMATS] = EnumSet.allOf(BarcodeFormat::class.java) | |
val results = ArrayList<Result>(1) | |
var readException: ReaderException? = null | |
try { | |
val multiReader = GenericMultipleBarcodeReader(reader) | |
val theResults = multiReader.decodeMultiple(binaryBitmap, hints) | |
if (theResults != null) { | |
results.addAll(theResults) | |
} | |
} catch (e: ReaderException) { | |
readException = e | |
} | |
if (results.isEmpty()) { | |
try { | |
val hintsPure = EnumMap<DecodeHintType, Any>(hints) | |
hintsPure[DecodeHintType.PURE_BARCODE] = true | |
val theResult = reader.decode(binaryBitmap, hintsPure) | |
if (theResult != null) { | |
results.add(theResult) | |
} | |
} catch (e: ReaderException) { | |
readException = e | |
} | |
} | |
if (results.isEmpty()) { | |
try { | |
val hybridBitmap = BinaryBitmap(HybridBinarizer(source)) | |
val theResult = reader.decode(hybridBitmap, hints) | |
if (theResult != null) { | |
results.add(theResult); | |
} | |
} catch (e: ReaderException) { | |
readException = e | |
} | |
} | |
if (results.isEmpty()) { | |
readException?.printStackTrace() | |
return null | |
} | |
return results[0].text // optional | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment