Android BitmapFactory.decodeFile(路径) 总是 returns 空

Android BitmapFactory.decodeFile(path) always returns null

我看到有很多与此问题相关的解决方案,但是 none 解决了我的问题。

我尝试使用 BitmapFactory.decodeFile(path) 函数将图像从 png 文件读取到位图(图像非常小~16px,所以没有我得到 OutOfMemoryException 的选项)。

我的文件层次结构尽可能简单:
-java
--example.com.app
---MainActivity.class
-res
--drawable
---array.png

我从 MainActivity 启动应用程序并单击按钮我尝试将 png 图像读取为位图。 我尝试通过以下方式将图像读取为位图:

  1. String path = Uri.parse("android.resource://"+R.class.getPackage().getName() +"/drawable/arrow.png").toString(); Bitmap bitmap = BitmapFactory.decodeFile(path);

  2. String path = Uri.parse("android.resource://drawable/arrow.png").toString(); Bitmap bitmap = BitmapFactory.decodeFile(path);

每次位图都是空的。你知道哪里会出问题吗?


Android API 27

或者使用BitmapFactory

的简单方法
BitmapFactory.decodeResource(getResources(), R.id.arrow);

或者您可以使用 context.getDrawable(R.drawable.arrow),这将 return 一个 drawable 准备好使用。 阅读更多相关信息 here

如果您仍想使用该路径,请使用 java.nio.file.Paths(folder1, folder2.. .. .) 阅读更多相关信息 here

你应该使用decodeResource,下面是一个例子:

BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(getResources(), R.id.arrow, options);
int imageHeight = options.outHeight;
int imageWidth = options.outWidth;
String imageType = options.outMimeType;

或者使用它的简单方法decodeResource

BitmapFactory.decodeResource(getResources(), R.id.arrow);