How to share a captured Image to another App in Android

04 Mar, 2020
Pre-requisite: How to open 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_PICTURESFile pictureDir
    = new File(
        Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_PICTURES),
        "CameraDemo");
In onCreate() method, check whether the directory pictureDir is present or not. If not then create the directory with the code belowif(!pictureDir.exists()){
    pictureDir.mkdirs();
}
Create another method called callCameraApp() to get the clicked image from external storage.Capture the image using IntentCreate a file to store the image in the pictureDir directory.Get the URI object of this image filePut 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 app 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..."));

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_PICTURESFile pictureDir
    = new File(
        Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_PICTURES),
        "CameraDemo");

File pictureDir
    = new File(
        Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_PICTURES),
        "CameraDemo");

In onCreate() method, check whether the directory pictureDir is present or not. If not then create the directory with the code belowif(!pictureDir.exists()){
    pictureDir.mkdirs();
}

if(!pictureDir.exists()){
    pictureDir.mkdirs();
}

Create another method called callCameraApp() to get the clicked image from external storage.Capture the image using IntentCreate a file to store the image in the pictureDir directory.Get the URI object of this image filePut the image on the Intent storage to be accessed from other modules of the app.Pass the image through intent to startActivityForResult()
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 app using intent.Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);

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..."));

startActivity(Intent.createChooser(emailIntent, "Send mail..."));

Below is the complete implementation of the above approach:
activity_main.xml
MainActivity.java
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?><RelativeLayout    xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:app="http://schemas.android.com/apk/res-auto"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context=".MainActivity">      <!--Textview with title "Camera_Demo!" is given by  -->         <TextView        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="Camera Demo!"        android:id="@+id/tv"        android:textSize="20sp"        android:textStyle="bold"        android:layout_centerHorizontal="true"        />      <!-- Add button to take a picture-->     <Button        android:id="@+id/button1"        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:layout_width="match_parent"        android:layout_height="match_parent"        android:id="@+id/imageView1"        android:layout_below="@id/button1"        /></RelativeLayout>
package com.example.camera_mail;  import android.Manifest;import android.content.Intent;import android.content.pm.PackageManager;import android.net.Uri;import android.os.Environment;import android.provider.MediaStore;import android.support.v4.app.ActivityCompat;import android.support.v4.content.ContextCompat;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.ImageView;import android.widget.Toast;  import java.io.File;  public class MainActivity    extends AppCompatActivity    implements View.OnClickListener {      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 Button b1;    private ImageView img1;      File pictureDir        = new File(            Environment.getExternalStoragePublicDirectory(                Environment.DIRECTORY_PICTURES),            "CameraDemo");    private Uri fileUri;      // The onCreate() method    @Override    protected void onCreate(Bundle savedInstanceState)    {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);          b1 = (Button)findViewById(R.id.button1);        img1 = (ImageView)findViewById(R.id.imageView1);        b1.setOnClickListener(this);        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 onClick(View arg0)    {        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)    {          if (requestCode == CAMERA_PIC_REQUEST            && resultCode == RESULT_OK) {            ImageView imageView                = (android.widget.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,        String[] permissions,        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..."));    }}
<?xml version="1.0" encoding="utf-8"?><manifest    xmlns:android="http://schemas.android.com/apk/res/android"    package="com.example.camera_mail">      <uses-permission        android:name="android.permission.WRITE_EXTERNAL_STORAGE"    />      <application        android:allowBackup="true"        android:icon="@mipmap/ic_launcher"        android:label="@string/app_name"        android:roundIcon="@mipmap/ic_launcher_round"        android:supportsRtl="true"        android:theme="@style/AppTheme">        <activity android:name=".MainActivity">            <intent-filter>                <action android:name="android.intent.action.MAIN" />                  <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>    </application>  </manifest>
Launch the appLaunch the appCapture the imageImage captured and two options given to userSelect the app to be share the captured image. Here GMail is selectedSend the captured image through mailSend the captured image through mailImage receivedImage received through mail
Launch the appLaunch the app
Launch the app
Capture the imageImage captured and two options given to user
Image captured and two options given to user
Select the app to be share the captured image. Here GMail is selected
Send the captured image through mailSend the captured image through mail
Send the captured image through mail
Image receivedImage received through mail
Image received through mail
android
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.