Share Image | Android Studio | Kotlin

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 Java

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.kt
package com.technifysoft.shareimagetext

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.ImageDecoder
import android.net.Uri
import android.os.Build
import android.provider.MediaStore
import android.widget.Toast
import androidx.core.content.FileProvider
import com.technifysoft.shareimagetext.databinding.ActivityMainBinding
import java.io.File
import java.io.FileOutputStream
import java.lang.Exception

class MainActivity : AppCompatActivity() {

    //viewbinding
    private var binding: ActivityMainBinding? = null

    //picked image uri will be saved in it
    private var imageUri: Uri? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding!!.root)

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

        //handle click, share image
        binding!!.shareImageBtn.setOnClickListener { shareImage() }
    }

    private fun shareImage() {
        val contentUri = getContentUri()
        val shareIntent = Intent(Intent.ACTION_SEND)
        shareIntent.type = "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  fun getContentUri(): Uri? {
        var bitmap: Bitmap? = null
        //get bitmap from uri
        try {
            bitmap = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                val source = ImageDecoder.createSource(contentResolver, imageUri!!)
                ImageDecoder.decodeBitmap(source)
            } else {
                MediaStore.Images.Media.getBitmap(contentResolver, imageUri)
            }
        } catch (e: Exception) {
            Toast.makeText(this, "" + e.message, 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();*/
        val imagesFolder = File(cacheDir, "images")
        var contentUri: Uri? = null
        try {
            imagesFolder.mkdirs() //create if not exists
            val file = File(imagesFolder, "shared_image.png")
            val stream = FileOutputStream(file)
            bitmap!!.compress(Bitmap.CompressFormat.PNG, 50, stream)
            stream.flush()
            stream.close()
            contentUri = FileProvider.getUriForFile(this, "com.technifysoft.shareimagetext.fileprovider", file)
        } catch (e: Exception) {
            Toast.makeText(this, "" + e.message, 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)