Share Image | Android Studio | Java

How to Share Image on button click - Android Studio

In this tutorial, we will learn how to share the Image. You will be able to share image picked from Camera/Gallery as Uri or bitmap also. When you click share button you will see a dialog/popup/window having all apps that are able to share the image.

>>Check For Kotlin

Step 1: Create XML Folder & XML Resource File


Create an xml folder under the res folder. For that right-click the res folder fand rom the popup window and click New > Folder > XML Resource Folder.

Create an XML Resource File under the xml folder. For that right-click the xml folder and from the popup window click New > XML Resource File and name file files_path.xml


Step 2: Code

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.technifysoft.shareimagetext">

    <uses-permission android:name="android.permission.READ_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/Theme.ShareImageText">
        <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>

        <!--Add file provider with your own package-->
        <provider
            android:name="androidx.core.content.FileProvider"
            android:authorities="com.technifysoft.shareimagetext.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/files_path" />
        </provider>

    </application>

</manifest>

files_path.xml
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">

    <cache-path
        name="shared_images"
        path="images/" />

    <external-path
        name="saved_images"
        path="MyImagesToShare/" />

</paths>

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical"
    android:padding="20dp"
    android:gravity="center"
    tools:context=".MainActivity">

    <!--ImageView: Pick image from gallery, you may pick from camera, get from internet etc-->
    <ImageView
        android:id="@+id/imageIv"
        android:layout_width="250dp"
        android:layout_height="250dp"
        android:src="@drawable/ic_baseline_image_24"
        android:scaleType="centerCrop"
        android:adjustViewBounds="true"/>

    <!--Button: Share image-->
    <com.google.android.material.button.MaterialButton
        android:id="@+id/shareImageBtn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Share Image"/>


</LinearLayout>

MainActivity.java
package com.technifysoft.shareimagetext;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.ImageDecoder;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;

import com.technifysoft.shareimagetext.databinding.ActivityMainBinding;

import java.io.File;
import java.io.FileOutputStream;

public class MainActivity extends AppCompatActivity {

    //viewbinding
    private ActivityMainBinding binding;

    //picked image uri will be saved in it
    private Uri imageUri = null; //Suppose you

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        imageUri = Uri.parse(""); //you may pick image from gallery/camera

        //handle click, share image
        binding.shareImageBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                shareImage();
            }
        });
    }

    private void shareImage() {
        Uri contentUri = getContentUri();

        Intent shareIntent = new Intent(Intent.ACTION_SEND);
        shareIntent.setType("image/png");
        shareIntent.putExtra(Intent.EXTRA_SUBJECT, "Subject Here"); //for sharing with email apps
        shareIntent.putExtra(Intent.EXTRA_STREAM, contentUri);
        shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        startActivity(Intent.createChooser(shareIntent, "Share Via"));
    }

    private Uri getContentUri() {
        Bitmap bitmap = null;
        //get bitmap from uri
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                ImageDecoder.Source source = ImageDecoder.createSource(getContentResolver(), imageUri);
                bitmap = ImageDecoder.decodeBitmap(source);
            } else {
                bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), imageUri);
            }
        } catch (Exception e) {
            Toast.makeText(this, "" + e.getMessage(), Toast.LENGTH_SHORT).show();
        }

        //if you want to get bitmap from imageview instead of uri then
        /*BitmapDrawable bitmapDrawable = (BitmapDrawable) binding.imageIv.getDrawable();
        bitmap = bitmapDrawable.getBitmap();*/

        File imagesFolder = new File(getCacheDir(), "images");
        Uri contentUri = null;
        try {
            imagesFolder.mkdirs(); //create if not exists
            File file = new File(imagesFolder, "shared_image.png");
            FileOutputStream stream = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG, 50, stream);
            stream.flush();
            stream.close();
            contentUri = FileProvider.getUriForFile(this, "com.technifysoft.shareimagetext.fileprovider", file);
        } catch (Exception e) {
            Toast.makeText(this, "" + e.getMessage(), Toast.LENGTH_SHORT).show();
        }

        return contentUri;
    }


}

Step 4: Output

Comments

Popular posts from this blog

Picture In Picture | Android Studio | Kotlin

Manage External Storage Permission | Android Studio | Kotlin

Add a Back Button to Action Bar Android Studio (Kotlin)