Friday, August 28, 2015

How to set ImageView image from Assets in Android

activity_main.xml

<androidx.constraintlayout.widget.ConstraintLayout
    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:background="#DCDCDC"
    android:padding="24dp"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Set ImageView Image From Assets"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <ImageView
        android:id="@+id/iv"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginTop="16dp"
        android:scaleType="centerCrop"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button" />

</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.java

package com.cfsuman.androidtutorials;

import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.app.Activity;
import android.widget.Button;
import android.widget.ImageView;
import java.io.IOException;
import java.io.InputStream;


public class MainActivity extends Activity {
        private ImageView mImageView;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_main);

                // Get the widgets reference from XML layout
                Button btn = findViewById(R.id.button);
                mImageView = findViewById(R.id.iv);

                // String variable to hold specified image file name
                final String imageFileName = "flower101.jpg";

                btn.setOnClickListener(v -> {
                        // Set ImageView image from drawable resource
                        mImageView.setImageBitmap(
                                getBitmapFromAssets(imageFileName)
                        );
                });
        }


        // Custom method to get assets folder image as bitmap
        private Bitmap getBitmapFromAssets(String fileName){
                AssetManager am = getAssets();
                InputStream is = null;
                try{
                        is = am.open(fileName);
                }catch(IOException e){
                        e.printStackTrace();
                }

                return BitmapFactory.decodeStream(is);
        }
}