BitmapFactory.decodeFile() returns null

2020-06-29 08:12发布

I am creating an Android app in which you copy an image from location x to location y. After the copying is complete I would like to see the picture in a ImageView. I know the images location, but no matter what I try I can't create a bitmap object of it.

The line which are causing my problems is this:

BitmapFactory.decodeFile(dir+s);

dir = getCacheDir().getAbsolutePath()+"/images/";

s = file name (eg. 1275123123.jpg)

If I create a File object with the same path, and call f.isFile(), it returns true.

Opening the image in either android or windows are not a problem.

3条回答
聊天终结者
2楼-- · 2020-06-29 08:47

I had a similar problem and what eventually solved it was creating FileInputStream(...) and decoding the stream. This is the code I used, I changed it to suite your case:

File location = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+ "/images");
File dest = new File(location, fileName + ".JPG");
FileInputStream fis;
fis = new FileInputStream(dest);
Bitmap img = BitmapFactory.decodeStream(fis);
查看更多
Animai°情兽
3楼-- · 2020-06-29 08:50

You have to add

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

permissions to you manifest.

And please don't forget to request runtime permission from user.

查看更多
家丑人穷心不美
4楼-- · 2020-06-29 08:52

Didn't you forget to add SD card access permissions READ_EXTERNAL_STORAGE and/or WRITE_EXTERNAL_STORAGE ?

查看更多
登录 后发表回答