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
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;
}
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.
WebView web = (WebView) findViewById(R.id.webView);
web.loadUrl("file:///android_asset/pract_recommend_section1_pic2.png");
web.getSettings().setBuiltInZoomControls(true);
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;
}
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)
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;
}