Wednesday, April 11, 2018

android kotlin - Save image to internal storage

MainActivity.kt

package com.cfsuman.kotlinexamples

import android.content.Context
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*
import android.graphics.Bitmap
import android.content.ContextWrapper
import android.graphics.drawable.BitmapDrawable
import android.net.Uri
import android.support.v4.content.ContextCompat
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.OutputStream
import java.util.*


class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // Click listener for button widget
        button.setOnClickListener{
            // Save the image in internal storage and get the uri
            val uri:Uri = saveImageToInternalStorage(R.drawable.flower8)

            // Display the internal storage saved image in image view
            image_view_saved.setImageURI(uri)

            // Show the saved image uri
            text_view.text = "Saved: $uri"
        }
    }


    // Method to save an image to internal storage
    private fun saveImageToInternalStorage(drawableId:Int):Uri{
        // Get the image from drawable resource as drawable object
        val drawable = ContextCompat.getDrawable(applicationContext,drawableId)

        // Get the bitmap from drawable object
        val bitmap = (drawable as BitmapDrawable).bitmap

        // Get the context wrapper instance
        val wrapper = ContextWrapper(applicationContext)

        // Initializing a new file
        // The bellow line return a directory in internal storage
        var file = wrapper.getDir("images", Context.MODE_PRIVATE)


        // Create a file to save the image
        file = File(file, "${UUID.randomUUID()}.jpg")

        try {
            // Get the file output stream
            val stream: OutputStream = FileOutputStream(file)

            // Compress bitmap
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream)

            // Flush the stream
            stream.flush()

            // Close stream
            stream.close()
        } catch (e: IOException){ // Catch the exception
            e.printStackTrace()
        }

        // Return the saved image uri
       return Uri.parse(file.absolutePath)
    }
}
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/root_layout"
    android:background="#ebffe5"
    android:padding="16dp"
    android:orientation="vertical"
    >
    <ImageView
        android:id="@+id/image_view_source"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:src="@drawable/flower8"
        />
    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Save Image To Internal Storage"
        android:layout_gravity="center_horizontal"
        android:layout_margin="10dp"
        />
    <TextView
        android:id="@+id/text_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="#ff2079"
        android:layout_margin="10dp"
        style="@style/Base.TextAppearance.AppCompat.Medium"
        />
    <ImageView
        android:id="@+id/image_view_saved"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        />
</LinearLayout>