Load an image from assets folder

后端 未结 8 1771
天命终不由人
天命终不由人 2020-11-28 07:06

I am trying to load an image from the asset folder and then set it to an ImageView. I know it\'s much better if I use the R.id.* for t

相关标签:
8条回答
  • 2020-11-28 07:41

    Here you are,

      public Bitmap getBitmapFromAssets(String fileName) {
        AssetManager assetManager = getAssets();
    
        InputStream istr = assetManager.open(fileName);
        Bitmap bitmap = BitmapFactory.decodeStream(istr);
        istr.close();
    
        return bitmap;
    }
    
    0 讨论(0)
  • 2020-11-28 07:41

    According to Android Developer Documentation loading with bitmap can degrade app performane.Here's a link! So doc suggest to use Glide library.

    If you want to load image from assets folder then using Glide library help you alots easier.

    just add dependencies to build.gradle (Module:app) from https://github.com/bumptech/glide

     dependencies {
      implementation 'com.github.bumptech.glide:glide:4.9.0'
      annotationProcessor 'com.github.bumptech.glide:compiler:4.9.0'
    }
    

    sample example :

    // For a simple view:
    @Override public void onCreate(Bundle savedInstanceState) {
      ...
      ImageView imageView = (ImageView) findViewById(R.id.my_image_view);
    
      Glide.with(this).load("file:///android_asset/img/fruit/cherries.jpg").into(imageView);
    }
    

    In case not worked by above method : Replace this object with view object from below code (only if you have Inflate method applied as below in your code).

     LayoutInflater mInflater =  LayoutInflater.from(mContext);
            view  = mInflater.inflate(R.layout.book,parent,false);
    
    0 讨论(0)
提交回复
热议问题