Skip to content

Instantly share code, notes, and snippets.

@Tougee
Created June 12, 2018 10:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Tougee/d8e8caf700ce0fcbc9f3ddf42984519d to your computer and use it in GitHub Desktop.
Save Tougee/d8e8caf700ce0fcbc9f3ddf42984519d to your computer and use it in GitHub Desktop.
Zxing Android decode QR code
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