Monday, October 24, 2022

How to set ImageView image from Assets in Android

MainActivity.java
package com.example.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);
        }
}

}

No comments:

Post a Comment