banner



How To Make A Camera App In Android Studio

How to Make Your Own Android Photographic camera App without Knowing How

Getting Started

Pre-requisites

  1. Android Studio 3.six+

Creating a New Project

new project template

Add CameraX to Project

                      // CameraX core library using camera2 implementation
implementation "androidx.camera:photographic camera-camera2:$camerax_version"
// CameraX Lifecycle Library
implementation "androidx.camera:camera-lifecycle:$camerax_version"
// CameraX View class
implementation "androidx.camera:camera-view:1.0.0-alpha14"
          compileOptions            {
sourceCompatibility JavaVersion. VERSION_1_8
targetCompatibility JavaVersion. VERSION_1_8
}

Add Required Permission

          <uses-characteristic android:name="android.hardware.camera.whatever"            />
<uses-permission android:proper name="android.permission.Photographic camera" />

Coding the Layout

          <Push button
android:id="@+id/camera_capture_button"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_marginBottom="50dp"
android:scaleType="fitCenter"
android:text="Take Photo"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
android:elevation="2dp"
/>

<androidx.camera.view.PreviewView
android:id="@+id/viewFinder"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>

Coding the Camera Logic

                      private var            imageCapture: ImageCapture? =            zero

private lateinit var

outputDirectory: File
private lateinit var cameraExecutor: ExecutorService
                      private fun            takePhoto() {
// Go a stable reference of the modifiable image capture apply case
val imageCapture = imageCapture ?: return // Create time-stamped output file to hold the image
val photoFile = File(
outputDirectory,
SimpleDateFormat(FILENAME_FORMAT, Locale.US
).format(System.currentTimeMillis()) + ".jpg")

// Create output options object which contains file + metadata
val outputOptions = ImageCapture.OutputFileOptions.Builder(photoFile).build()

// Set image capture listener, which is triggered after photograph has
// been taken
imageCapture.takePicture(
outputOptions, ContextCompat.getMainExecutor(this), object : ImageCapture.OnImageSavedCallback {
override fun onError(exc: ImageCaptureException) {
Log.e(TAG, "Photo capture failed: ${exc.bulletin}", exc)
}

override fun onImageSaved(output: ImageCapture.OutputFileResults) {
val savedUri = Uri.fromFile(photoFile)
val msg = "Photo capture succeeded: $savedUri"
Toast.makeText(baseContext, msg, Toast.LENGTH_SHORT).show()
Log.d(TAG, msg)
}
})
}

                      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.Architect()
.build()
.also {
information technology
.setSurfaceProvider(viewFinder.createSurfaceProvider())
}

imageCapture

= ImageCapture.Builder()
.build()

// Select back photographic camera as a default
val cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA try {
// Unbind apply cases before rebinding
cameraProvider.unbindAll()

// Demark use cases to camera
cameraProvider.bindToLifecycle(
this, cameraSelector, preview, imageCapture)

} catch(exc: Exception) {
Log.e(TAG, "Use case binding failed", exc)
}

}, ContextCompat.getMainExecutor(this))
}

                      private fun            allPermissionsGranted() =            REQUIRED_PERMISSIONS.all                        {
ContextCompat.checkSelfPermission(
baseContext, it) == PackageManager.PERMISSION_GRANTED
}@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
individual fun getOutputDirectory(): File {
val mediaDir = externalMediaDirs.firstOrNull()?.let {
File(information technology, resources.getString(R.string.app_name)).employ { mkdirs() } }
return if
(mediaDir != null && mediaDir.exists())
mediaDir else filesDir
}

override fun onRequestPermissionsResult(
requestCode: Int, permissions: Array<String>, grantResults:
IntArray) {
if (requestCode == REQUEST_CODE_PERMISSIONS) {
if (allPermissionsGranted()) {
startCamera()
} else {
Toast.makeText(this,
"Permissions not granted by the user.",
Toast.LENGTH_SHORT).evidence()
cease()
}
}
}

                      override fun            onDestroy() {
super.onDestroy()
cameraExecutor.shutdown()
}

companion object {
private const val TAG = "CameraXBasic"
private const val FILENAME_FORMAT
= "yyyy-MM-dd-HH-mm-ss-SSS"
private const val REQUEST_CODE_PERMISSIONS
= ten
private val REQUIRED_PERMISSIONS = arrayOf(Manifest.permission.Camera)
}

Running the App

Conclusion

Source: https://aboyi.medium.com/how-to-make-your-own-android-camera-app-without-knowing-how-aca3364358b

Posted by: mcdonaldyone1997.blogspot.com

0 Response to "How To Make A Camera App In Android Studio"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel