How to Open Camera Through Intent and Display Captured Image in Android?
The purpose of this article is to show how to open a Camera from inside an App and click the image and then display this image inside the same app. An android application has been developed in this article to achieve this. The opening of the Camera from inside our app is achieved with the help of the ACTION_IMAGE_CAPTURE Intent of MediaStore class.
This image shows the Image clicked by the camera and set in Imageview. When the app is opened, it displays the "Camera" Button to open the camera. When pressed, ACTION_IMAGE_CAPTURE Intent gets started by the MediaStore class. When the image is captured, it is displayed in the image view.
Step by Step Implementation
Step 1: Create a New Project in Android Studio
To create a new project in the Android Studio, please refer to How to Create/Start a New Project in Android Studio?
Step 2: Working with manifest file
Navigate to app > manifests > AndroidManifest.xml and add the following code under the <application> tag.
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
Step 3: Create a xml file for setting file paths
Navigate to app > res > xml, right click on the folder and select, New > XML Resource File and set the name as file_paths.xml. Now add the following code to the file
file_paths.xml:
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<cache-path name="images" path="images/" />
</paths>
Step 4: Add dependency for image loading
Navigate to Gradle Scripts > build.gradle.kts (Module :app) and the following dependency under the dependencies{} scope.
dependencies {
...
implementation("com.github.bumptech.glide:glide:4.16.0")
}
Step 5: Working activity_main.xml
Next, go to the activity_main.xml file, which represents the UI of the project. Below is the code for the activity_main.xml file. Comments are added inside the code to understand the code in more detail.
- A Button to open the Camera
- An ImageView to display the captured image
Also, Assign the ID to each component along with other attributes as shown in the image and the code below.
Syntax:
android:id="@+id/id_name"
Here the given IDs are as follows:
- Camera Button: camera_button
- ImageView: click_image
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- Camera Button -->
<Button
android:id="@+id/camera_open"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Open Camera"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
android:layout_marginTop="32dp" />
<!-- ImageView for Captured Image -->
<ImageView
android:id="@+id/click_image"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintTop_toBottomOf="@id/camera_open"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
android:layout_margin="16dp" />
</androidx.constraintlayout.widget.ConstraintLayout>
Step 6: Working with the MainActivity File
Go to the MainActivity File and refer to the following code. Below is the code for the MainActivity File. Comments are added inside the code to understand the code in more detail. We will instantiate the components made in the XML file (Camera Button, ImageView) using the findViewById() method. This method binds the created object to the UI Components with the help of the assigned ID.
General Syntax:
val object: ComponentType = findViewById(R.id.IdOfTheComponent)
The Syntax for Components Used:
val openCamera: Button = findViewById(R.id.camera_open)
val clickedImage: ImageView = findViewById(R.id.click_image)
Setting up Operations on the Camera Button and ImageView.
Add the listener to the Camera button. This will be used to open the camera when the user clicks on the button.
This is done as follows:
openCamera.setOnClickListener { }
Now, create an activity result launcher to open camera.
This is done as follows:
if (requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK) {
// load image
}
Now use the activity result launcher to get the result, here is the captured image.
This is done as follows:
val cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE).apply {
putExtra(MediaStore.EXTRA_OUTPUT, photoUri)
addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
}
Then set the image received as a result of Camera intent in the ImageView for display.
Glide.with(this).load(photoUri).into(clickedImage)
package org.geeksforgeeks.demo;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.widget.Button;
import android.widget.ImageView;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;
import com.bumptech.glide.Glide;
import java.io.File;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
// Declare UI elements
private Button openCamera;
private ImageView clickedImage;
// Variables to hold the file and its Uri
private File photoFile;
private Uri photoUri;
// Unique request code for identifying the camera intent result
private static final int CAMERA_REQUEST_CODE = 1001;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
openCamera = findViewById(R.id.camera_open);
clickedImage = findViewById(R.id.click_image);
openCamera.setOnClickListener(v -> {
try {
// Create a temporary image file to store the captured photo
photoFile = createImageFile();
// Get a content URI for the file using FileProvider
// This allows secure sharing of the file with the camera app
photoUri = FileProvider.getUriForFile(
this,
getPackageName() + ".fileprovider", // FileProvider authority (defined in manifest)
photoFile
);
// Create an intent to launch the camera app
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Tell the camera app where to save the image
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
// Grant temporary write permission to the camera app for the URI
cameraIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
// Start the camera app and wait for the result
startActivityForResult(cameraIntent, CAMERA_REQUEST_CODE);
} catch (IOException e) {
e.printStackTrace();
}
});
}
// Function to create a temporary image file in the cache directory
private File createImageFile() throws IOException {
// Create a directory inside cache to store images (if not already created)
File imageDir = new File(getCacheDir(), "images");
if (!imageDir.exists()) {
imageDir.mkdirs();
}
// Create a temp file with prefix "captured_" and suffix ".jpg"
return File.createTempFile("captured_", ".jpg", imageDir);
}
// Deprecated but still usable for handling activity results (like camera)
@Override
@Deprecated
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Check if the result is from the camera and was successful
if (requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK) {
// Load the captured image from the URI into the ImageView using Glide
Glide.with(this).load(photoUri).into(clickedImage);
}
}
}
package org.geeksforgeeks.demo
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.widget.Button
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.FileProvider
import com.bumptech.glide.Glide
import java.io.File
class MainActivity : AppCompatActivity() {
// Declare UI elements
private lateinit var openCamera: Button
private lateinit var clickedImage: ImageView
// Variables to hold the file and its Uri
private lateinit var photoFile: File
private lateinit var photoUri: Uri
// Unique request code for identifying the camera intent result
private val CAMERA_REQUEST_CODE = 1001
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
openCamera = findViewById(R.id.camera_open)
clickedImage = findViewById(R.id.click_image)
openCamera.setOnClickListener {
// Create a temporary image file to store the captured photo
photoFile = createImageFile()
// Get a content URI for the file using FileProvider
// This allows secure sharing of the file with the camera app
photoUri = FileProvider.getUriForFile(
this,
"${packageName}.fileprovider", // FileProvider authority (defined in manifest)
photoFile
)
// Create an intent to launch the camera app
val cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE).apply {
// Tell the camera app where to save the image
putExtra(MediaStore.EXTRA_OUTPUT, photoUri)
// Grant temporary write permission to the camera app for the URI
addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
}
// Start the camera app and wait for the result
startActivityForResult(cameraIntent, CAMERA_REQUEST_CODE)
}
}
// Function to create a temporary image file in the cache directory
private fun createImageFile(): File {
// Create a directory inside cache to store images (if not already created)
val imageDir = File(cacheDir, "images").apply { mkdirs() }
// Create a temp file with prefix "captured_" and suffix ".jpg"
return File.createTempFile("captured_", ".jpg", imageDir)
}
// Deprecated but still usable for handling activity results (like camera)
@Deprecated("Deprecated in Java")
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
// Check if the result is from the camera and was successful
if (requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK) {
// Load the captured image from the URI into the ImageView using Glide
Glide.with(this).load(photoUri).into(clickedImage)
}
}
}