Android BitmapFactory.decodeFile(path) always returns null

Viewed 1171

I see that is a lot of solutions related to this issue, but none of this solved my problem.

I try to read image from png file to bitmap (image is very small ~16px so there is no option that I got OutOfMemoryException) using BitmapFactory.decodeFile(path) function.

My file hierarchy is as simple as possible:
-java
--example.com.app
---MainActivity.class
-res
--drawable
---array.png

I launch application from MainActivity and on button click I try to read png image to bitmap. I try to read image to bitmap in the following ways:

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

Everytime bitmap is null. Do you know where could be a problem?


Android API 27

2 Answers

Or use the simple method of BitmapFactory

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

Or you can use context.getDrawable(R.drawable.arrow) which will return a drawable that is ready to use. Read more about this here

If you would like to still use the path then use java.nio.file.Paths(folder1, folder2.. .. .) Read more about this here

You should use decodeResource, below is an example:

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;

Or use its simple way decodeResource.

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