21

我有一个文件本地保存到应用程序的私有存储中。我已经验证它存在,但是每当我调用它时,BitmapFactory.decodeFile它总是返回null

如果我将文件保存为资源并使用ImageView.setImageResource,它总是显示得很好。

问题是什么?

这是片段:

filename = "test.png";

if (doesFileExist(filename))
    Bitmap bMap = BitmapFactory.decodeFile(filename);

我也试过:

Bitmap bMap = BitmapFactory.decodeFile(getFilesDir().getPath()
                    + filename);
4

8 回答 8

33

这个问题之前已经回答过,例如这里: BitmapFactory.decodeFile return null even image exists

这正是我所需要的:

String fname=new File(getFilesDir(), "test.png").getAbsolutePath();
于 2011-05-16T06:06:45.730 回答
5

尝试使用 InputStream,而不是使用 BitmapFactory.decodeFile:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) { 
    super.onActivityResult(requestCode, resultCode, imageReturnedIntent); 

    if(resultCode == RESULT_OK){          
        Uri selectedImage = imageReturnedIntent.getData();
        InputStream imageStream = getContentResolver().openInputStream(selectedImage);
        Bitmap yourSelectedImage = BitmapFactory.decodeStream(imageStream);
于 2016-09-21T12:58:17.957 回答
3

伙计们,应该以特殊方式引用存储在应用程序资源中的文件。例如,如果文件位于资产中并命名为“myfile.png”,则必须将其引用为:

String uriString="file:///android_asset/myfile.png";
Uri uri=Uri.parse(uriString);
于 2011-05-16T05:17:49.550 回答
3

BitmapFactory.decodeFile期望没有该方案的文件路径。即没有file://在开始。

如果你正在处理一个 Uri,不要只是.toString()它,而是调用.getPath()它,并将它传递给方法。

于 2018-10-22T10:22:39.637 回答
1

After adding the required permissions (READ_EXTERNAL_STORAGE, WRITE_EXTERNAL_STORAGE)

You need to add this line to manifests: android:requestLegacyExternalStorage="true"

enter image description here

于 2021-02-15T21:27:08.103 回答
0

你可以试试 fileList() 吗?它

返回一个字符串数组,命名与此上下文的应用程序包关联的私有文件。

于 2011-05-16T04:47:10.107 回答
0

对我来说,我从本地保存的 URL 获取图像,例如“file:///storage/emulated/0/....”(我使用 Phonegap 插件来捕获图像。插件给了我图像路径,我需要在本机代码中使用)

这是对我有用的代码片段。

String captured_image_info = "file:///storage/emulated/0/Android/data/com.testapp/cache/1493809796526.jpg"
Uri uri=Uri.parse(captured_image_info);
largeLog("uri", "" + uri);

InputStream imageStream = getContentResolver().openInputStream(uri);

Bitmap bm = BitmapFactory.decodeStream(imageStream);

ByteArrayOutputStream baos = new ByteArrayOutputStream();

bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object

byte[] decodedBytes = baos.toByteArray();

Bitmap img_captured_image = BitmapFactory.decodeByteArray(decodedBytes, 0, decodedBytes.length);
于 2017-05-03T11:16:58.550 回答
0

You need to setup run-time permissions for Manifest.permission.READ_EXTERNAL_STORAGE If you don't you'll get a null without getting any error message or even an indication in the Log. Note that you need to request the permissions both in the Manifest and at run time.

于 2020-02-07T13:51:12.600 回答