Load an image from assets folder

AndroidImageAssets

Android Problem Overview


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 this, but the premise is I don't know the id of the image. Basically, I'm trying to dynamically load the image via its filename.

For example, I randomly retrieve an element in the database representing let's say a 'cow', now what my application would do is to display an image of a 'cow' via the ImageView. This is also true for all element in the database. (The assumption is, for every element there is an equivalent image)

thanks in advance.

EDIT

forgot the question, how do I load the image from the asset folder?

Android Solutions


Solution 1 - Android

Checkout this code . IN this tutorial you can find how to load image from asset folder.

// load image

try 
{
	// get input stream
	InputStream ims = getAssets().open("avatar.jpg");
	// load image as Drawable
	Drawable d = Drawable.createFromStream(ims, null);
	// set image to ImageView
	mImage.setImageDrawable(d);
    ims .close();
}
catch(IOException ex) 
{
    return;
}

Solution 2 - Android

Here you are,

  public Bitmap getBitmapFromAssets(String fileName) throws IOException {
    AssetManager assetManager = getAssets();

    InputStream istr = assetManager.open(fileName);
    Bitmap bitmap = BitmapFactory.decodeStream(istr);
    istr.close();

    return bitmap;
}

Solution 3 - Android

If you know the filename in the code, calling this won't be a problem:

ImageView iw= (ImageView)findViewById(R.id.imageView1);  
int resID = getResources().getIdentifier(drawableName, "drawable",  getPackageName());
iw.setImageResource(resID);

Your filename will be the same name as drawableName so you won't have to deal with assets.

Solution 4 - Android

Some of these answers may answer the question but I never liked any of them so I ended up writing this, it my help the community.

Get Bitmap from assets:

public Bitmap loadBitmapFromAssets(Context context, String path)
{
    InputStream stream = null;
    try
    {
        stream = context.getAssets().open(path);
        return BitmapFactory.decodeStream(stream);
    }
    catch (Exception ignored) {} finally
    {
        try
        {
            if(stream != null)
            {
                stream.close();
            }
        } catch (Exception ignored) {}
    }
    return null;
}

Get Drawable from assets:

public Drawable loadDrawableFromAssets(Context context, String path)
{
    InputStream stream = null;
    try
    {
        stream = context.getAssets().open(path);
        return Drawable.createFromStream(stream, null);
    }
    catch (Exception ignored) {} finally
    {
        try
        {
            if(stream != null)
            {
                stream.close();
            }
        } catch (Exception ignored) {}
    }
    return null;
}

Solution 5 - Android

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);

Solution 6 - Android

public static Bitmap getImageFromAssetsFile(Context mContext, String fileName) {
        Bitmap image = null;
        AssetManager am = mContext.getResources().getAssets();
        try {
            InputStream is = am.open(fileName);
            image = BitmapFactory.decodeStream(is);
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return image;
    }

Solution 7 - Android

This worked in my use case:

AssetManager assetManager = getAssets();
ImageView imageView = (ImageView) findViewById(R.id.imageView);
try (
        //declaration of inputStream in try-with-resources statement will automatically close inputStream
        // ==> no explicit inputStream.close() in additional block finally {...} necessary
        InputStream inputStream = assetManager.open("products/product001.jpg")
) {
    Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
    imageView.setImageBitmap(bitmap);
} catch (IOException ex) {
    //ignored
}

(see also https://javarevisited.blogspot.com/2014/10/right-way-to-close-inputstream-file-resource-in-java.html)

Solution 8 - Android

WebView web = (WebView) findViewById(R.id.webView);
web.loadUrl("file:///android_asset/pract_recommend_section1_pic2.png");
web.getSettings().setBuiltInZoomControls(true);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionkishidpView Question on Stackoverflow
Solution 1 - AndroidChiragView Answer on Stackoverflow
Solution 2 - AndroidosayilganView Answer on Stackoverflow
Solution 3 - AndroidErolView Answer on Stackoverflow
Solution 4 - AndroidNicolas TylerView Answer on Stackoverflow
Solution 5 - AndroidPrakash KarkeeView Answer on Stackoverflow
Solution 6 - AndroidAnil SinghaniaView Answer on Stackoverflow
Solution 7 - AndroidYvesView Answer on Stackoverflow
Solution 8 - AndroidEvgenyView Answer on Stackoverflow