'Android Studio getPixel of CameraX Bitmap error (Kotlin)
I made an android app (Android Studio + Kotlin) that uses CameraX. So this is my code to start the camera:
private fun startCamera() {
val cameraProviderFuture = ProcessCameraProvider.getInstance(this)
cameraProviderFuture.addListener(Runnable {
// Used to bind the lifecycle of cameras to the lifecycle owner
val cameraProvider: ProcessCameraProvider = cameraProviderFuture.get()
// Preview
val preview = Preview.Builder()
.build()
.also {
it.setSurfaceProvider(viewFinder.surfaceProvider)
}
// Select back camera as a default
val cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA
try {
// Unbind use cases before rebinding
cameraProvider.unbindAll()
// Bind use cases to camera
cameraProvider.bindToLifecycle(
this, cameraSelector, preview
)
} catch (exc: Exception) {
Log.e(TAG, "Use case binding failed", exc)
}
}, ContextCompat.getMainExecutor(this))
}
Now I wanted to get a bitmap of the viewFinder so that I can determine the color of the pixel in the center:
val bitmap = viewFinder.bitmap
val pixel = bitmap?.getPixel(width / 2, height / 2 - 30)
val pixel2 = if (pixel != null) pixel else -1
bitmap is Bitmap? and pixel is Int?
When I run the app everything works completely fine but then sometimes it crashes and shoots out this message:
at com.example.colorblind.MainActivity$onCreate$r$1.run(MainActivity.kt:116)
Line 116 is the line with val pixel = bitmap?.getPixel(width / 2, height / 2 - 30). If I then add a line before the code so that it hops to line 117 everything works perfectly fine again until the same error occurs. Then I need to change the line again. How can I fix this problem because I can't publish the app like this if it sometimes randomly crashes while opening.
I hope I was able to explain the problem properly.
EDIT
This is the only message I get when it crashes:
2022-02-16 20:43:53.123 7337-7337/com.example.colorblind E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.colorblind, PID: 7337
java.lang.IllegalArgumentException: y must be < bitmap.height()
at android.graphics.Bitmap.checkPixelAccess(Bitmap.java:1958)
at android.graphics.Bitmap.getPixel(Bitmap.java:1863)
at com.example.colorblind.MainActivity$onCreate$r$1.run(MainActivity.kt:116)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
