Creating an App that Integrates Camera and Gallery
In this tutorial, we will explain in detail how to integrate the camera and gallery in an Android app using Kotlin.
We will implement two features: taking photos with the camera and selecting images from the gallery.
Ultimately, we will develop a simple app that displays the image on the screen when the user takes or selects a photo.
Table of Contents
- Prerequisites
- App Setup and Permission Requests
- Taking Photos with the Camera
- Selecting Photos from the Gallery
- Conclusion
Prerequisites
To proceed with this tutorial, the following prerequisites are required.
- Latest version of Android Studio installed
- Basic knowledge of Kotlin programming language
- Experience in basic Android app development
App Setup and Permission Requests
The first step is to create an Android project and set up the necessary permission requests.
Open Android Studio and create a new project using the ‘Empty Activity’ template.
1. Gradle Setup
Add the following dependencies to the build.gradle (Module: app)
file to enable camera and gallery functionalities.
dependencies { implementation 'androidx.appcompat:appcompat:1.3.1' implementation 'androidx.core:core-ktx:1.6.0' implementation 'androidx.activity:activity-ktx:1.2.2' implementation 'com.google.android.material:material:1.4.0' }
2. Adding Permissions to AndroidManifest.xml
Add the required permissions to access the camera and gallery in the AndroidManifest.xml
file.
<uses-permission android:name="android.permission.CAMERA" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
3. Requesting Permissions
For devices running Android 6.0 (API 23) or higher, you must request permissions from users at runtime.
Add the following code to the MainActivity.kt
file to request permissions.
class MainActivity : AppCompatActivity() { private val REQUEST_CODE_PERMISSIONS = 10 private val REQUIRED_PERMISSIONS = arrayOf(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) if (!allPermissionsGranted()) { ActivityCompat.requestPermissions(this, REQUIRED_PERMISSIONS, REQUEST_CODE_PERMISSIONS) } } private fun allPermissionsGranted() = REQUIRED_PERMISSIONS.all { ContextCompat.checkSelfPermission(baseContext, it) == PackageManager.PERMISSION_GRANTED } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array, grantResults: IntArray) { if (requestCode == REQUEST_CODE_PERMISSIONS) { if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // Permission granted } else { // Permission denied Toast.makeText(this, "Permission is required.", Toast.LENGTH_SHORT).show() } } } }
Taking Photos with the Camera
We will implement a feature that allows the user to take photos using the camera.
In this process, we will also see how to display the results of the photos taken in the app.
1. Setting Up Camera Intent
Use the following code to create a function that executes the camera intent.
At this time, use the URI generated from the intent to save the path of the photo taken.
private lateinit var photoUri: Uri private fun openCamera() { val cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE) photoUri = FileProvider.getUriForFile(this, "${BuildConfig.APPLICATION_ID}.fileprovider", createImageFile()) cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri) startActivityForResult(cameraIntent, REQUEST_IMAGE_CAPTURE) } private fun createImageFile(): File { val timeStamp: String = SimpleDateFormat("yyyyMMdd_HHmmss").format(Date()) val storageDir: File = getExternalFilesDir(Environment.DIRECTORY_PICTURES)!! return File.createTempFile("JPEG_${timeStamp}_", ".jpg", storageDir).apply { // The file path is returned here. currentPhotoPath = absolutePath } }
2. Handling the Photo Capture Result
Override the onActivityResult
method to handle the URI of the photo taken.
Use this URI to display the image in the ImageView.
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == Activity.RESULT_OK) { val bitmap = BitmapFactory.decodeFile(currentPhotoPath) imageView.setImageBitmap(bitmap) } }
Selecting Photos from the Gallery
Now, we will add a feature that allows the user to select images from the gallery.
This functionality can also be easily implemented through intents.
1. Setting Up Gallery Intent
Create a function that allows the user to select images from the gallery.
private fun openGallery() { val galleryIntent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI) startActivityForResult(galleryIntent, REQUEST_IMAGE_PICK) }
2. Method for Handling Selected Images
Receive the URI of the selected image and display it in the ImageView.
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) when (requestCode) { REQUEST_IMAGE_PICK -> { if (resultCode == Activity.RESULT_OK) { data?.data?.let { uri -> imageView.setImageURI(uri) } } } // Previous code... } }
Conclusion
In this tutorial, we learned how to create an Android application that allows for taking and selecting images by integrating the camera and gallery.
We demonstrated that complex tasks can be handled simply with Kotlin’s powerful features and Android’s various APIs.
Building upon this guide to add your own features can also be a great learning experience.
Thank you!