Welcome folks today in this blog post we will be capturing image
from camera and display it inside the imageView
widget and also saving the image inside the gallery
. All the full source code of the application is shown below.
Get Started
In order to get started you need to make a new android
project inside the android studio and then you will see the below directory
structure as shown below at the end
of the project.
Now we need to edit the AndroidManifest.xml
file you need to include the camera
and external storage
permission as shown below
AndroidManifest.xml
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 |
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools"> <uses-permission android:name="android.permission.CAMERA" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <application android:allowBackup="true" android:dataExtractionRules="@xml/data_extraction_rules" android:fullBackupContent="@xml/backup_rules" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/Theme.CameraApp" tools:targetApi="31"> <activity android:name=".MainActivity" android:exported="true"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> |
Now we need to edit the activity_main.xml
layout file where we have the imageView
widget where we will be displaying the captured
image from the camera and also we will have the button
to capture the image.
activity_main.xml
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 |
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/main_layout" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <ImageView android:id="@+id/image_view" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_above="@id/button_capture" android:scaleType="fitCenter" android:adjustViewBounds="true" /> <Button android:id="@+id/button_capture" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true" android:text="Capture Image" android:onClick="captureImage"/> </RelativeLayout> |
And now we need to edit the MainActivity.java
file and copy paste the following code
MainActivity.java
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 |
package com.example.cameraapp; import android.Manifest; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.provider.MediaStore; import android.view.View; import android.widget.ImageView; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import java.io.File; import java.io.FileOutputStream; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; public class MainActivity extends AppCompatActivity { private static final int REQUEST_CAMERA_PERMISSION_CODE = 1; private static final int REQUEST_IMAGE_CAPTURE = 2; private ImageView imageView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); imageView = findViewById(R.id.image_view); } public void captureImage(View view) { // Check if camera permission is granted if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { // Request camera permission if not granted ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, REQUEST_CAMERA_PERMISSION_CODE); return; } // Launch camera intent to capture image Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(intent, REQUEST_IMAGE_CAPTURE); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); // Handle result of image capture intent if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) { // Get captured image as bitmap Bundle extras = data.getExtras(); Bitmap imageBitmap = (Bitmap) extras.get("data"); // Set captured image to ImageView imageView.setImageBitmap(imageBitmap); // Save captured image to gallery saveImageToGallery(imageBitmap); } } private void saveImageToGallery(Bitmap imageBitmap) { // Get storage directory for saved images File storageDir = Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_PICTURES); // Create new file name for saved image String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()) .format(new Date()); String fileName = "IMG_" + timeStamp + ".jpg"; // Create new file for saved image File imageFile = new File(storageDir, fileName); try { // Write image bitmap to file FileOutputStream outputStream = new FileOutputStream(imageFile); imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream); outputStream.flush(); outputStream.close(); // Add image to gallery Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE); mediaScanIntent.setData(Uri.fromFile(imageFile)); sendBroadcast(mediaScanIntent); // Show success message Toast.makeText(this, "Image Saved Successully", Toast.LENGTH_SHORT).show(); } catch (Exception e) { e.printStackTrace(); Toast.makeText(this, "Failed to save Image", Toast.LENGTH_SHORT).show(); } } } |
As you can see in the above java
code we are getting the reference of the imageView
and the button
widget using their id's
which we have given inside the xml
code. And then we are binding the onClick
listener to the button to capture
the image from the camera and inside it we are first of all asking the user
to grant the permissions
of camera
at runtime and then when the user takes the picture
from the camera app and then we are saving the image
inside the gallery