BitmapFactory在Android Nougat上拍摄照片后无法从Uri解码位图



我试图拍照然后使用照片。这是我所做的。

我的设备是 Nexus 6p(Android 7.1.1)

首先,我创建了一个Uri

Uri mPicPath = UriUtil.fromFile(this, UriUtil.createTmpFileForPic());
//Uri mPicPath = UriUtil.fromFile(this, UriUtil.createFileForPic());

然后,我开始Intent

Intent intent = ActivityUtils.getTakePicIntent(mPicPath);
if (intent.resolveActivity(getPackageManager()) != null) {
    startActivityForResult(intent, RequestCode.TAKE_PIC);
}

最后,我在onActivityResult上处理了此Uri

if (requestCode == RequestCode.TAKE_PIC) {
    if (resultCode == RESULT_OK && mPicPath != null) {
        Bitmap requireBitmap = BitmapFactory.decodeFile(mPicPath.getPath());
        //path is like this: /Download/Android/data/{@applicationId}/files/Pictures/JPEG_20170216_173121268719051242.jpg
        requireBitmap.recycle();//Here NPE was thrown.
    }
}

与此同时,这里有 UriUtil

public class UriUtil {
    public static File createFileForPic() throws IOException {
        String fileName = "JPEG_" + new SimpleDateFormat("yyyyMMdd_HHmmssSSS", Locale.getDefault()).format(new Date()) + ".jpg";
        File storageDic = SPApplication.getInstance().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        return new File(storageDic, fileName);
    }
    public static File createTmpFileForPic() throws IOException {
        String fileName = "JPEG_" + new SimpleDateFormat("yyyyMMdd_HHmmssSSS", Locale.getDefault()).format(new Date());
        File storageDic = SPApplication.getInstance().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        return File.createTempFile(fileName, ".jpg", storageDic);
    }
    public static Uri fromFile(@NonNull Context context, @NonNull File file) {
        if (context == null || file == null) {
            throw new RuntimeException("context or file can't be null");
        }
        if (ActivityUtils.requireSDKInt(Build.VERSION_CODES.N)) {
            return FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".file_provider", file);
        } else {
            return Uri.fromFile(file);
        }
    }
}

getTakePicIntent(Uri)

public static Intent getTakePicIntent(Uri mPicPath) {
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, mPicPath);
    if (!ActivityUtils.requireSDKInt(Build.VERSION_CODES.KITKAT_WATCH)) {//in pre-KitKat devices, manually grant uri permission.
        List<ResolveInfo> resInfoList = SPApplication.getInstance().getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
        for (ResolveInfo resolveInfo : resInfoList) {
            String packageName = resolveInfo.activityInfo.packageName;
            SPApplication.getInstance().grantUriPermission(packageName, mPicPath, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }
    } else {
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
    }
    return intent;
}

requireSDKInt

public static boolean requireSDKInt(int sdkInt) {
    return Build.VERSION.SDK_INT >= sdkInt;
}

除了 android Nougat(7.x.x)外,所有内容都在不同的Android API上起作用。甚至提供了" fileprovider",'requientBitMap'始终返回为" null"。

读取日志后,FileNotFoundException是从BitmapFactory扔出的。就像:

BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: /Download/Android/data/{@applicationId}/files/Pictures/JPEG_20170216_1744551601425984925.jpg (No such file or directory)

看来一切都很清楚,但我仍然不明白。

怎么可能?显然我创建了一个File!我该如何解决?有什么想法吗?

我尝试了您的代码。这是我的try.https://github.com/raghunandankavi2010/samplesandroid/tree/master/master/stackoverflowtest。

请查看此博客https://commonsware.com/blog/2016/03/15/how-consume-content-uri.html

在博客中心软件中提到您不应该做new File (mPicPath.getPath())

相反,您应该在onActivityResult

中使用以下内容
try {
       InputStream ims = getContentResolver().openInputStream(mPicPath);
       // just display image in imageview
       imageView.setImageBitmap(BitmapFactory.decodeStream(ims));
    } catch (FileNotFoundException e) {
            e.printStackTrace();
    }

和xml

 <external-files-path name="external_files" path="path" />

注意:这是您拥有的内容。在我的手机上,我得到了下面的URI。仅在nexus6p上测试。

content://com.example.raghu.stackoverflowtest.fileprovider/external_files/pictures/pictures/jpeg_20170424_161429696969143693693160.jpg

更多在文件提供商https://developer.android.com/reference/android/support/v4/content/fileprovider.html

尝试此功能可能是您从中获得路径。这对我有用

@TargetApi(Build.VERSION_CODES.KITKAT)
public static String getRealPathFromURI_API19(Context context, Uri uri) {
    if (HelperFunctions.isExternalStorageDocument(uri)) {
        // ExternalStorageProvider
        final String docId = DocumentsContract.getDocumentId(uri);
        final String[] split = docId.split(":");
        final String type = split[0];
        if ("primary".equalsIgnoreCase(type)) {
            return Environment.getExternalStorageDirectory() + "/"
                    + split[1];
        }
    } else if (HelperFunctions.isDownloadsDocument(uri)) {
        // DownloadsProvider
        final String id = DocumentsContract.getDocumentId(uri);
        final Uri contentUri = ContentUris.withAppendedId(
                Uri.parse("content://downloads/public_downloads"),
                Long.valueOf(id));
        return HelperFunctions.getDataColumn(context, contentUri, null, null);
    } else if (HelperFunctions.isMediaDocument(uri)) {

        final String docId = DocumentsContract.getDocumentId(uri);
        final String[] split = docId.split(":");
        final String type = split[0];
        Uri contentUri = null;
        if ("image".equals(type)) {
            contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
        } else if ("video".equals(type)) {
            contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
        } else if ("audio".equals(type)) {
            contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        }
        final String selection = "_id=?";
        final String[] selectionArgs = new String[]{split[1]};
        return HelperFunctions.getDataColumn(context, contentUri, selection,
                selectionArgs);

    } else if ("content".equalsIgnoreCase(uri.getScheme())) {
        // Return the remote address
        if (HelperFunctions.isGooglePhotosUri(uri))
            return uri.getLastPathSegment();
        return HelperFunctions.getDataColumn(context, uri, null, null);
    }
    // File
    else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }
    return null;
}

这是我的静态功能辅助类别,用于上述。

 public class HelperFunction{
       /**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is ExternalStorageProvider.
 */
public static boolean isExternalStorageDocument(Uri uri) {
    return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is DownloadsProvider.
 */
public static boolean isDownloadsDocument(Uri uri) {
    return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is MediaProvider.
 */
public static boolean isMediaDocument(Uri uri) {
    return "com.android.providers.media.documents".equals(uri.getAuthority());
}

/**
 * @param uri
 *            The Uri to check.
 * @return Whether the Uri authority is Google Photos.
 */
public static boolean isGooglePhotosUri(Uri uri) {
    return "com.google.android.apps.photos.content".equals(uri
            .getAuthority());
}

}

它看起来很像{@applicationId}实际上应该包含应用程序的包装ID。实际上,文件夹不存在,因此不能编写或读取文件。看起来像 spapplication.getInstance()。getExternalFilesDir(vosing.directory_pictures);不是返回有效的路径。

牛轧糖和上一个更新正在使用此代码

要获取牛轧糖数据库的真实路径,请使用此功能,并通过onActivityResult中的数据字段中的URI,然后从路径中获取文件。

    public String getPath(Uri uri) {
    Cursor cursor = getContentResolver().query(uri, null, null, null, null);
    cursor.moveToFirst();
    String document_id = cursor.getString(0);
    document_id = document_id.substring(document_id.lastIndexOf(":") + 1);
    cursor.close();
    cursor = getContentResolver().query(
            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
            null, MediaStore.Images.Media._ID + " = ? ", new String[]{document_id}, null);
    cursor.moveToFirst();
    String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
    cursor.close();
    return path;
}

您应该使用FileProvider。您可以参考此提案以进行所需的更改。

尝试滑行。

1。添加Glide依赖性到App/build.gradle

repositories {
   mavenCentral() // jcenter() works as well because it pulls from Maven Central
}
dependencies {
   compile 'com.github.bumptech.glide:glide:3.7.0'
   compile 'com.android.support:support-v4:19.1.0'
 }

2。使用Glide

加载图像
Glide.with(context).load(new File(uri.getPath())).placeholder(R.drawable.placeholder).into(imageView);

Glide.load(new File(uri.getPath())) // Uri of the picture
.transform(new CircleTransform(..))
.into(imageView);

最新更新