-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy pathMainActivity.kt
More file actions
executable file
·292 lines (252 loc) · 11.5 KB
/
MainActivity.kt
File metadata and controls
executable file
·292 lines (252 loc) · 11.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
package io.scanbot.example
import android.Manifest
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Color
import android.graphics.Matrix
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.view.ViewCompat
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.updateLayoutParams
import io.scanbot.common.Result
import io.scanbot.common.mapSuccess
import io.scanbot.common.onFailure
import io.scanbot.common.onSuccess
import io.scanbot.example.common.applyEdgeToEdge
import io.scanbot.sdk.ScanbotSDK
import io.scanbot.sdk.camera.CaptureInfo
import io.scanbot.sdk.camera.FrameHandler
import io.scanbot.sdk.camera.PictureCallback
import io.scanbot.sdk.document.DocumentAutoSnappingController
import io.scanbot.sdk.document.DocumentScannerFrameHandler
import io.scanbot.sdk.documentscanner.DocumentDetectionResult
import io.scanbot.sdk.documentscanner.DocumentDetectionStatus
import io.scanbot.sdk.documentscanner.DocumentScanner
import io.scanbot.sdk.image.ImageRef
import io.scanbot.sdk.imageprocessing.ScanbotSdkImageProcessor
import io.scanbot.sdk.process.ImageProcessor
import io.scanbot.sdk.ui.PolygonView
import io.scanbot.sdk.ui.camera.ScanbotCameraXView
import io.scanbot.sdk.ui.camera.ShutterButton
import io.scanbot.sdk.util.PolygonHelper
/**
This example uses the SDK APIs introduced in Scanbot SDK v8.x.x.
Please check the official documentation for more details:
Result API https://docs.scanbot.io/android/document-scanner-sdk/detailed-setup-guide/result-api/
ImageRef API https://docs.scanbot.io/android/document-scanner-sdk/detailed-setup-guide/image-ref-api/
*/
class MainActivity : AppCompatActivity(), DocumentScannerFrameHandler.ResultHandler {
private lateinit var cameraView: ScanbotCameraXView
private lateinit var polygonView: PolygonView
private lateinit var resultView: ImageView
private lateinit var userGuidanceHint: TextView
private lateinit var autoSnappingToggleButton: Button
private lateinit var shutterButton: ShutterButton
private lateinit var documentScannerFrameHandler: DocumentScannerFrameHandler
private var lastUserGuidanceHintTs = 0L
private var flashEnabled = false
private var autoSnappingEnabled = true
private val ignoreOrientationMismatch = true
override fun onCreate(savedInstanceState: Bundle?) {
supportRequestWindowFeature(WindowCompat.FEATURE_ACTION_BAR_OVERLAY)
super.onCreate(savedInstanceState)
askPermission()
setContentView(R.layout.activity_main)
supportActionBar?.hide()
applyEdgeToEdge(this.findViewById(R.id.root_view))
cameraView = findViewById<View>(R.id.camera) as ScanbotCameraXView
polygonView = findViewById<View>(R.id.polygonView) as PolygonView
shutterButton = findViewById(R.id.shutterButton)
autoSnappingToggleButton = findViewById(R.id.autoSnappingToggle)
val scanbotSDK = ScanbotSDK(this)
scanbotSDK.createDocumentScanner().onSuccess { documentScanner ->
documentScanner.apply {
// Please note: https://docs.scanbot.io/document-scanner-sdk/android/features/document-scanner/ui-components/
setConfiguration(copyCurrentConfiguration().apply {
parameters.apply {
this.ignoreOrientationMismatch = ignoreOrientationMismatch
this.acceptedSizeScore = 75
this.acceptedAngleScore = 60
}
})
}
documentScannerFrameHandler =
DocumentScannerFrameHandler.attach(cameraView, documentScanner)
cameraView.addPictureCallback(object : PictureCallback() {
override fun onPictureTaken(image: ImageRef, captureInfo: CaptureInfo) {
processPictureTaken(image, documentScanner)
}
})
documentScannerFrameHandler.addResultHandler(polygonView.documentScannerResultHandler)
documentScannerFrameHandler.addResultHandler(this@MainActivity)
val autoSnappingController =
DocumentAutoSnappingController.attach(cameraView, documentScannerFrameHandler)
// Please note: https://docs.scanbot.io/document-scanner-sdk/android/features/document-scanner/ui-components/#sensitivity
autoSnappingController.setSensitivity(0.85f)
// In this example we demonstrate how to lock the orientation of the UI (Activity)
// as well as the orientation of the taken picture to portrait.
cameraView.lockToPortrait(true)
// See https://docs.scanbot.io/document-scanner-sdk/android/features/document-scanner/ui-components/#preview-mode
//cameraView.setPreviewMode(io.scanbot.sdk.camera.CameraPreviewMode.FIT_IN)
cameraView.setCameraOpenCallback {
cameraView.postDelayed({
// Shutter sound is ON by default. You can disable it:
// cameraView.setShutterSound(false)
cameraView.continuousFocus()
cameraView.useFlash(flashEnabled)
}, 700)
}
resultView = findViewById<View>(R.id.result) as ImageView
polygonView.setFillColor(POLYGON_FILL_COLOR)
polygonView.setFillColorOK(POLYGON_FILL_COLOR_OK)
userGuidanceHint = findViewById(R.id.userGuidanceHint)
shutterButton.setOnClickListener { cameraView.takePicture(false) }
shutterButton.visibility = View.VISIBLE
findViewById<View>(R.id.flashToggle).setOnClickListener {
flashEnabled = !flashEnabled
cameraView.useFlash(flashEnabled)
}
autoSnappingToggleButton.setOnClickListener {
autoSnappingEnabled = !autoSnappingEnabled
setAutoSnapEnabled(autoSnappingController, autoSnappingEnabled)
}
autoSnappingToggleButton.post {
setAutoSnapEnabled(
autoSnappingController,
autoSnappingEnabled
)
}
}.onFailure { error ->
when (error) {
is Result.InvalidLicenseError -> {
Toast.makeText(this@MainActivity, "License is invalid: ${error.message}", Toast.LENGTH_LONG).show()
}
else -> {
Toast.makeText(this@MainActivity, "${error.message}", Toast.LENGTH_LONG).show()
}
}
}
}
private fun askPermission() {
if (ContextCompat.checkSelfPermission(
this,
Manifest.permission.CAMERA
) != PackageManager.PERMISSION_GRANTED
) {
ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.CAMERA), 999)
}
}
override fun handle(
result: Result<DocumentDetectionResult>,
frame: FrameHandler.Frame
): Boolean {
// Here you are continuously notified about document scanning results.
// For example, you can show a user guidance text depending on the current scanning status.
result.onSuccess { data ->
userGuidanceHint.post {
showUserGuidance(data.status)
}
}
return false // typically you need to return false
}
private fun showUserGuidance(result: DocumentDetectionStatus) {
if (!autoSnappingEnabled) {
return
}
if (System.currentTimeMillis() - lastUserGuidanceHintTs < 400) {
return
}
// Make sure to reset the default polygon fill color (see the ignoreBadAspectRatio case).
polygonView.setFillColor(POLYGON_FILL_COLOR)
when (result) {
DocumentDetectionStatus.OK -> {
userGuidanceHint.text = "Don't move"
userGuidanceHint.visibility = View.VISIBLE
}
DocumentDetectionStatus.OK_BUT_TOO_SMALL -> {
userGuidanceHint.text = "Move closer"
userGuidanceHint.visibility = View.VISIBLE
}
DocumentDetectionStatus.OK_BUT_BAD_ANGLES -> {
userGuidanceHint.text = "Perspective"
userGuidanceHint.visibility = View.VISIBLE
}
DocumentDetectionStatus.ERROR_NOTHING_DETECTED -> {
userGuidanceHint.text = "No Document"
userGuidanceHint.visibility = View.VISIBLE
}
DocumentDetectionStatus.ERROR_TOO_NOISY -> {
userGuidanceHint.text = "Background too noisy"
userGuidanceHint.visibility = View.VISIBLE
}
DocumentDetectionStatus.OK_BUT_BAD_ASPECT_RATIO -> {
if (ignoreOrientationMismatch) {
userGuidanceHint.text = "Don't move"
// change polygon color to "OK"
polygonView.setFillColor(POLYGON_FILL_COLOR_OK)
} else {
userGuidanceHint.text = "Wrong aspect ratio.\n Rotate your device."
}
userGuidanceHint.visibility = View.VISIBLE
}
DocumentDetectionStatus.ERROR_TOO_DARK -> {
userGuidanceHint.text = "Poor light"
userGuidanceHint.visibility = View.VISIBLE
}
else -> userGuidanceHint.visibility = View.GONE
}
lastUserGuidanceHintTs = System.currentTimeMillis()
}
private fun processPictureTaken(image: ImageRef, documentScanner: DocumentScanner) {
// Run document scanning on original image:
val polygon =
documentScanner.run(image).getOrNull()?.pointsNormalized ?: throw IllegalStateException(
"No document detected"
)
val polygonCrop =
polygon.takeIf { it.isNotEmpty() && it.size == 4 } ?: PolygonHelper.getFullPolygon()
val documentImage = ScanbotSdkImageProcessor.create()
.crop(image, polygonCrop)
.mapSuccess { documentImage ->
ScanbotSdkImageProcessor.create().resize(documentImage, 200).getOrReturn()
}.getOrNull()
resultView.post {
resultView.setImageBitmap(documentImage?.toBitmap()?.getOrNull())
}
// continue scanning
cameraView.postDelayed({
cameraView.continuousFocus()
cameraView.startPreview()
}, 1000)
}
private fun setAutoSnapEnabled(
autoSnappingController: DocumentAutoSnappingController,
enabled: Boolean
) {
autoSnappingController.isEnabled = enabled
documentScannerFrameHandler.isEnabled = enabled
polygonView.visibility = if (enabled) View.VISIBLE else View.GONE
autoSnappingToggleButton.text = "Automatic ${if (enabled) "ON" else "OFF"}"
if (enabled) {
shutterButton.showAutoButton()
} else {
shutterButton.showManualButton()
userGuidanceHint.visibility = View.GONE
}
}
companion object {
private val POLYGON_FILL_COLOR = Color.parseColor("#55ff0000")
private val POLYGON_FILL_COLOR_OK = Color.parseColor("#4400ff00")
}
}