Pre-requisite: How to open a Camera through Intent and capture an image
In this article, we will try to send the captured image (from this article) to other apps using Android Studio.
Approach: The image captured gets stored on the external storage. Hence we need to request permission to access the files from the user. So take permission to access external storage permission in the manifest file.
Here pictureDir(File) is pointing to the directory of external storage named DIRECTORY_PICTURES
File pictureDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),”CameraDemo”);
In the onCreate() method, check whether the directory pictureDir is present or not. If not then create the directory with the code below
if(!pictureDir.exists()) { pictureDir.mkdirs(); }
Create another method called callCameraApp() to get the clicked image from external storage.
- Capture the image using Intent
- Create a file to store the image in the pictureDir directory.
- Get the URI object of this image file
- Put the image on the Intent storage to be accessed from other modules of the app.
- Pass the image through intent to startActivityForResult()
Share this image to other apps using intent.
Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
For the sake of this article, we will be selecting Gmail and will be sending this image as an attachment in a mail.
startActivity(Intent.createChooser(emailIntent, "Send mail..."));
Below is the Complete Implementation of the above Approach:
Step By Step Implementation
Step 1: Create a New Project in Android Studio
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. The code for that has been given in both Java and Kotlin Programming Language for Android.
Step 2: Adding the Required Permissions in the Manifest File
Navigate to the app > AndroidManifest.xml file and add the below permissions to it.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Step 3: Working with the XML Files
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.
XML
<? xml version = "1.0" encoding = "utf-8" ?> android:layout_width = "match_parent" android:layout_height = "match_parent" tools:context = ".MainActivity" > <!-- Textview with title "Camera_Demo!" is given by --> < TextView android:id = "@+id/tv" android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:layout_centerHorizontal = "true" android:text = "Camera Demo!" android:textSize = "20sp" android:textStyle = "bold" /> <!-- Add button to take a picture --> < Button android:id = "@+id/button1" android:onClick = "takePicture" android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:layout_below = "@id/tv" android:layout_marginTop = "50dp" android:text = "Take Picture" android:textSize = "20sp" android:textStyle = "bold" /> <!-- Add ImageView to display the captured image --> < ImageView android:id = "@+id/imageView1" android:layout_width = "match_parent" android:layout_height = "match_parent" android:layout_below = "@id/button1" /> </ RelativeLayout > |
Step 4: 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.
Java
import android.Manifest; import android.content.Intent; import android.content.pm.PackageManager; 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.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import java.io.File; public class MainActivity extends AppCompatActivity { private static final int CAMERA_PIC_REQUEST = 1337 ; private static final int REQUEST_EXTERNAL_STORAGE_RESULT = 1 ; private static final String FILE_NAME = "image01.jpg" ; private ImageView img1; File pictureDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "CameraDemo" ); private Uri fileUri; @Override protected void onCreate(Bundle savedInstanceState) { super .onCreate(savedInstanceState); setContentView(R.layout.activity_main); img1 = findViewById(R.id.imageView1); if (!pictureDir.exists()) { pictureDir.mkdirs(); } } // Open the camera app to capture the image public void callCameraApp() { Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); File image = new File(pictureDir, FILE_NAME); fileUri = Uri.fromFile(image); intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); startActivityForResult(intent, CAMERA_PIC_REQUEST); } public void takePicture(View view) { if (ContextCompat.checkSelfPermission( this , Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { callCameraApp(); } else { if (ActivityCompat.shouldShowRequestPermissionRationale( this , Manifest.permission.WRITE_EXTERNAL_STORAGE)) { Toast.makeText( this , "External storage permission" + " required to save images" , Toast.LENGTH_SHORT).show(); } ActivityCompat.requestPermissions( this , new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_EXTERNAL_STORAGE_RESULT); } } protected void onActivityResult( int requestCode, int resultCode, Intent data) { super .onActivityResult(requestCode, resultCode, data); if (requestCode == CAMERA_PIC_REQUEST && resultCode == RESULT_OK) { ImageView imageView = findViewById(R.id.imageView1); File image = new File(pictureDir, FILE_NAME); fileUri = Uri.fromFile(image); imageView.setImageURI(fileUri); emailPicture(); } else if (resultCode == RESULT_CANCELED) { Toast.makeText( this , "You did not click the photo" , Toast.LENGTH_SHORT).show(); } } @Override public void onRequestPermissionsResult( int requestCode, @NonNull String[] permissions, @NonNull int [] grantResults) { if (requestCode == REQUEST_EXTERNAL_STORAGE_RESULT) { if (grantResults[ 0 ] == PackageManager.PERMISSION_GRANTED) { callCameraApp(); } else { Toast.makeText( this , "External write permission" + " has not been granted, " + " cannot saved images" , Toast.LENGTH_SHORT).show(); } } else { super .onRequestPermissionsResult(requestCode, permissions, grantResults); } } // Function to send the image through mail public void emailPicture() { Toast.makeText( this , "Now, sending the mail" , Toast.LENGTH_LONG).show(); Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND); emailIntent.setType( "application/image" ); emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{ // default receiver id "enquiry@geeksforgeeks.org" }); // Subject of the mail emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "New photo" ); // Body of the mail emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, "Here's a captured image" ); // Set the location of the image file to be added as an attachment emailIntent.putExtra(Intent.EXTRA_STREAM, fileUri); // Start the email activity to with the prefilled information startActivity(Intent.createChooser(emailIntent, "Send mail..." )); } } |
Kotlin
import android.Manifest import android.content.Intent import android.content.pm.PackageManager import android.net.Uri import android.os.Build import android.os.Bundle import android.os.Environment import android.provider.MediaStore 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 class MainActivity : AppCompatActivity() { companion object { private const val CAMERA_PIC_REQUEST = 1337 private const val REQUEST_EXTERNAL_STORAGE_RESULT = 1 private const val FILE_NAME = "image01.jpg" } private lateinit var img1: ImageView private lateinit var fileUri: Uri var pictureDir = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) { File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "CameraDemo" ) } else { TODO( "VERSION.SDK_INT < FROYO" ) } override fun onCreate(savedInstanceState: Bundle?) { super .onCreate(savedInstanceState) setContentView(R.layout.activity_main) img1 = findViewById(R.id.imageView1) if (!pictureDir.exists()) { pictureDir.mkdirs() } } // Open the camera app to capture the image private fun callCameraApp() { val image = File(pictureDir, FILE_NAME) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.CUPCAKE) { val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE) fileUri = Uri.fromFile(image) intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri) startActivityForResult(intent, CAMERA_PIC_REQUEST) } else { TODO( "VERSION.SDK_INT < CUPCAKE" ) } } fun takePicture() { if (ContextCompat.checkSelfPermission( this , Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { callCameraApp() } else { if (ActivityCompat.shouldShowRequestPermissionRationale( this , Manifest.permission.WRITE_EXTERNAL_STORAGE)) { Toast.makeText( this , "External storage permission" + " required to save images" , Toast.LENGTH_SHORT).show() } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.DONUT) { ActivityCompat.requestPermissions( this , arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), REQUEST_EXTERNAL_STORAGE_RESULT) } } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super .onActivityResult(requestCode, resultCode, data) if (requestCode == CAMERA_PIC_REQUEST && resultCode == RESULT_OK) { val imageView = findViewById<ImageView>(R.id.imageView1) val image = File(pictureDir, FILE_NAME) fileUri = Uri.fromFile(image) imageView.setImageURI(fileUri) emailPicture() } else if (resultCode == RESULT_CANCELED) { Toast.makeText( this , "You did not click the photo" , Toast.LENGTH_SHORT).show() } } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) { if (requestCode == REQUEST_EXTERNAL_STORAGE_RESULT) { if (grantResults[ 0 ] == PackageManager.PERMISSION_GRANTED) { callCameraApp() } else { Toast.makeText( this , "External write permission" + " has not been granted, " + " cannot saved images" , Toast.LENGTH_SHORT).show() } } else { super .onRequestPermissionsResult(requestCode, permissions, grantResults) } } // Function to send the image through mail private fun emailPicture() { Toast.makeText( this , "Now, sending the mail" , Toast.LENGTH_LONG).show() val emailIntent = Intent(Intent.ACTION_SEND) emailIntent.type = "application/image" // default receiver id emailIntent.putExtra(Intent.EXTRA_EMAIL, arrayOf( "enquiry@geeksforgeeks.org" )) // Subject of the mail emailIntent.putExtra(Intent.EXTRA_SUBJECT, "New photo" ) // Body of the mail emailIntent.putExtra(Intent.EXTRA_TEXT, "Here's a captured image" ) // Set the location of the image file to be added as an attachment emailIntent.putExtra(Intent.EXTRA_STREAM, fileUri) // Start the email activity to with the prefilled information startActivity(Intent.createChooser(emailIntent, "Send mail..." )) } } |