How to share a captured Image to another App in Android

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:

  1. 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.
  2. Here pictureDir(File) is pointing to the directory of external storage named DIRECTORY_PICTURES
    File pictureDir
        = new File(
            Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_PICTURES),
            "CameraDemo");
    
  3. In 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();
    }
    
  4. 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()
  5. Share this image to other app using intent.
    Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
    
  6. 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:

activity_main.xml

filter_none

edit
close

play_arrow

link
brightness_4
code

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    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>

chevron_right


MainActivity.java

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


AndroidManifest.xml

filter_none

edit
close

play_arrow

link
brightness_4
code

<?xml version="1.0" encoding="utf-8"?>
<manifest
    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>

chevron_right


  1. Launch the app
    UI of App

    Launch the app

  2. Capture the image
    image clicked and giving two options to user

    Image captured and two options given to user

  3. Select the app to be share the captured image. Here GMail is selected
  4. Send the captured image through mail

    Send the captured image through mail

  5. Image received

    Image received through mail

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
Practice Tags :


1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.