Skip to main content

Scanning a barcode from an image | Android Document Scanner

The Scanbot SDK Barcode Scanner is a versatile tool that can not only perform live detection of barcodes, but can also extract content from still images imported from the gallery or any other source.

Integration

The Example Apps are available to see the Barcode scanner in action and to gain a comprehensive understanding of how to integrate it into your project:

Add Barcode Detection as a Dependency

ScanbotBarcodeDetector is available with SDK Package 1. To use ScanbotBarcodeDetector, add the following dependencies:

implementation("io.scanbot:sdk-package-1:$latestSdkVersion")
implementation("io.scanbot:sdk-barcode-assets:$latestSdkVersion")
caution

Please do not use multiple scanners at the same time. For example, do not combine generic document scanner, health insurance scanner, text data scanner, etc. at the same time! Each scanner instance requires a lot of memory, GPU, and processor resources. Using multiple scanners will lead to performance issues for the entire application.

Initialize the SDK

Before using the Scanbot SDK, you must initialize it in your Application class:

import io.scanbot.sdk.ScanbotSDKInitializer

class ExampleApplication : Application() {

override fun onCreate() {
super.onCreate()

// Initialize the Scanbot Scanner SDK:
ScanbotSDKInitializer()
.license(this, licenseKey)
// TODO: other configuration calls
.initialize(this)
}
}
caution

ScanbotSDKInitializer#prepareBarcodeScannerBlobs(true) is deprecated and removed from the API. All Barcode Scanner assets will be prepared automatically if the appropriate assets dependency is added.

To select an image from the photo library and run detection on it, a class for an image import contract is created using the modern Android result API.

class ImportImageContract(private val context: Context) : ActivityResultContract<Unit, Bitmap?>() {
override fun createIntent(context: Context, input: Unit): Intent {
// An image is selected from the photo library and document detection is run on it:
val imageIntent = Intent()
imageIntent.type = "image/*"
imageIntent.action = Intent.ACTION_GET_CONTENT
imageIntent.putExtra(Intent.EXTRA_LOCAL_ONLY, false)
imageIntent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, false)

return Intent.createChooser(imageIntent, "Select a picture")
}

private fun processGalleryResult(data: Intent): Bitmap? {
val imageUri = data.data
return MediaStore.Images.Media.getBitmap(context.contentResolver, imageUri)
}

override fun parseResult(resultCode: Int, intent: Intent?): Bitmap? {
return if (resultCode == Activity.RESULT_OK && intent != null) {
return processGalleryResult(intent)
} else {
null
}
}
}

To run the gallery call and get a Bitmap using ImportImageContract, the following code is used:

 val galleryImageLauncher =
registerForActivityResult(ImportImageContract(this)) { resultEntity ->
lifecycleScope.launch(Dispatchers.Default) {
val activity = this@MainActivity
val sdk = ScanbotSDK(activity)
if (!sdk.licenseInfo.isValid) {
withContext(Dispatchers.Main) {
Toast.makeText(
activity,
"License has expired!",
Toast.LENGTH_LONG
).show()
}
} else {
resultEntity?.let { bitmap ->
// Image processing is carried out
// processImage()
}
}
}
}
findViewById<View>(R.id.import_image).setOnClickListener {
galleryImageLauncher.launch(Unit)
}

Create the Scanner

  val sdk = ScanbotSDK(activity)
val barcodeDetector = sdk.createBarcodeDetector()
caution

Calling createBarcodeDetector() will create a new ScanbotBarcodeDetector and initialize memory for it. Please don't create new scanners for each of the import actions if you are expecting more than one import operation.

ScanbotBarcodeDetector provides two detection methods:

  • fun detectFromBitmap(bitmap: Bitmap, frameOrientation: Int): BarcodeScanningResult?
  • fun detectFromJpeg(jpeg: ByteArray, frameOrientation: Int): BarcodeScanningResult?

These methods detect barcodes on an image (JPG file or Bitmap) regardless of the image source (e.g., scanned document image, image picked from photo library, etc).

Detecting Barcodes

Use the Scanbot SDK to detect the desired barcode on the imported bitmap.

    private fun processImage(
barcodeDetector: ScanbotBarcodeDetector,
bitmap: Bitmap
) {
if (!sdk.licenseInfo.isValid) { return; }
barcodeDetector.modifyConfig { //specify list of barcode formats to be expected in document if needs.}
val result = barcodeDetector.detectFromBitmap(bitmap, 0)
// handle the detected barcode(s) from result
}

Input Arguments

  • bitmap: Bitmap: Bitmap of the source image.
  • jpeg: ByteArray: byte array of the JPG source image.
  • frameOrientation: Int: frame orientation degrees.

Handling the Result

Below is an example of presenting the BarcodeScanningResult data separated by a newline character and shown in a Toast notification.

val barcodeData = result!!
val barcodesTextResult = StringBuilder()
for (item in barcodeData.barcodeItems) {
barcodesTextResult.append(item.barcodeFormat.name + "\n" + item.text)
.append("\n")
.append("-------------------")
.append("\n")
}
Toast.makeText(activity, barcodesTextResult.toString(), Toast.LENGTH_LONG).show()

Full API references for the result class are available here.

Want to scan longer than one minute?

Generate your free "no-strings-attached" Trial License and properly test the Scanbot SDK.

Get your free Trial License

What do you think of this documentation?