android - 如何从 Assets 加载图像?

标签 android assets

我需要从 Assets 加载图像以避免在某些特定情况下调整 POT 图像大小的 froyo 2.2.2 错误。避免它的方法是从 Assets 目录加载图像文件。

我正在尝试这样做:

String imagePath = "radiocd5.png";
AssetManager mngr = context.getAssets();
// Create an input stream to read from the asset folder
InputStream is = null;
try {
    is = mngr.open(imagePath);
} catch (IOException e1) { e1.printStackTrace();}
    
//Get the texture from the Android resource directory
//InputStream is = context.getResources().openRawResource(R.drawable.radiocd5);
Bitmap bitmap = null;
try {
    //BitmapFactory is an Android graphics utility for images
    bitmap = BitmapFactory.decodeStream(is);

} finally {
    //Always clear and close
    try {
        is.close();
        is = null;
    } catch (IOException e) {}
}

但是我在 is.close();

行上得到了 NullPointerException

我捕获了一个 FileNotFoundException: radiocd5.png,但该文件在我的 Assets 目录中:S

我做错了什么?该文件名为 radiocd5.png,位于 assets 目录

最佳答案

您可以按照我的教程显示 Assets 中的数据:https://xjaphx.wordpress.com/2011/10/02/store-and-use-files-in-assets/
加载图像和文本以显示的示例。

我现在添加了所提供链接的相关部分 (以防地震什么的);-) Taifun

// 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);
}
catch(IOException ex) {
    return;
}

关于android - 如何从 Assets 加载图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7645268/

相关文章:

Android 自定义适配器 - 不会返回 View ?

java - 如何模块化长代码

javascript - Android webview 不显示带有外部 js 链接的 html

ruby-on-rails - 错误:Sprockets::FileNotFound: 找不到 Heroku 的文件 'application.scss'

ruby-on-rails - 如何使 "assets:precompile"不加载数据库? ( rails )

android - 如何打开并读取 my/assets 目录中的文本文件?

php - Laravel 5.1 - 获取当前路线

android - 如何知道我的 Android BroadcastReceiver 是否已注册

android - 检查操作栏在 android 中是隐藏还是可见

android - 文本输入布局 : RuntimeException - Failed to resolve attribute at index 24