android 从资源文件夹加载图像

bmvo0sr5  于 2022-11-27  发布在  Android
关注(0)|答案(9)|浏览(193)

我尝试从asset文件夹加载一个图像,然后将其设置为ImageView。我知道如果使用R.id.*会更好,但前提是我不知道图像的id。基本上,我尝试通过文件名动态加载图像。
例如,我随机检索database中的一个元素,比如说一个 'cow',现在我的应用程序将通过ImageView显示一个 'cow' 的图像。对于database中的所有元素也是如此。(假设每个元素都有一个等价的图像)
先谢谢你了。

编辑

我忘记了一个问题,如何从asset文件夹加载图像?

im9ewurl

im9ewurl1#

checkout 这个code。在这个教程中,你可以找到如何从asset文件夹加载图像。
//加载图像

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;
}
z3yyvxxp

z3yyvxxp2#

给你,

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

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

    return bitmap;
}
xnifntxz

xnifntxz3#

如果您知道代码中的文件名,调用它就不会有问题:

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

您的文件名将与drawableName同名,因此您不必处理资源。

xlpyo6sf

xlpyo6sf4#

这些答案中的一些可能回答了这个问题,但我从来没有喜欢过其中的任何一个,所以我最终写了这篇文章,这是我对社区的帮助。
从资源获取Bitmap

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

从资源获取Drawable

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;
}
jtjikinw

jtjikinw5#

根据Android开发者文档,使用位图加载会降低应用性能。这里是a link!因此文档建议使用Glide库。
如果您想从资产文件夹中加载图像,则使用Glide库可以帮助您更轻松地进行操作。
只需添加依赖项即可从https://github.com/bumptech/glide构建.gradle(模块:app)

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

示例:

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

如果不采用上述方法:将 this 对象替换为以下代码中的 view 对象(仅当您在代码中应用了如下Inflate方法时)。

LayoutInflater mInflater =  LayoutInflater.from(mContext);
        view  = mInflater.inflate(R.layout.book,parent,false);
nbysray5

nbysray56#

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;
    }
o4tp2gmn

o4tp2gmn7#

这在我的用例中很有效:

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也称为https://javarevisited.blogspot.com/2014/10/right-way-to-close-inputstream-file-resource-in-java.html

jgzswidk

jgzswidk8#

您只需使用Kotlin扩展函数,其中String引用fileName

fun String.assetsToBitmap(context: Context): Bitmap? {
    return try {
        val assetManager = context.assets
        val inputStream = assetManager.open(this)
        val bitmap = BitmapFactory.decodeStream(inputStream)
        inputStream.close()
        bitmap
    } catch (e: Exception) {
        e.printStackTrace()
        null
    }
}

样品使用

val myBitmap = "sample.png".assetsToBitmap(context)
f0ofjuux

f0ofjuux9#

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

相关问题