无法从文件中加载图像:// Picasso 中的路径

Cannot load Image from file:// path in Picasso

我正在尝试使用 Picasso 从图库中将图像加载到 ImageView

代码如下

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(resultCode!= Activity.RESULT_OK) return;

        switch (requestCode) {
            case PICK_GALLERY_IMAGE_REQUEST: {
                Uri imageUri = data.getData();
                Log.d(DEBGUG_TAG,"Image URI: "+imageUri.toString());


                Picasso picasso = Picasso.with(getApplicationContext());
                picasso.setLoggingEnabled(true);
                picasso.load(imageUri).error(R.drawable.c).into(testImgView, new com.squareup.picasso.Callback(){

                    @Override
                    public void onSuccess() {
                        Log.d(DEBGUG_TAG,"Success loading image from uri:PICASSO");
                    }

                    @Override
                    public void onError() {
                        Log.d(DEBGUG_TAG,"Cannot load image");
                    }
                });

问题是从图库中选择图片时 returns 文件路径

D/debug: Image URI: file:///storage/emulated/0/DCIM/Camera/IMG_20170126_211524.jpg

这似乎不适用于 Picasso,因为 returns 错误并在错误方法中记录 D/debug: Cannot load image

然而,从 returns Uri 喜欢的另一个应用程序中选择相同的图片: D/debug: Image URI: content://com.google.android.apps.photos.contentprovider/-1/1/content%3A%2F%2Fmedia%2Fexternal%2Fimages%2Fmedia%2F90455/ORIGINAL/NONE/1757236944 成功。

有什么方法可以从文件路径加载图像?

试试下面的代码:

File imgFile = new  File("/sdcard/Images/test_image.jpg");

if(imgFile.exists()){

    Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());

    ImageView myImage = (ImageView) findViewById(R.id.imageviewTest);

    myImage.setImageBitmap(myBitmap);

}

尝试 ImageView 的内置方法 setImageURI 用于本地文件

testImgView.setImageURI(Uri.parse(imageUri));

不要使用 file:// 就像这样使用它 file:

 Uri targetUri = data.getData();
            if (data.toString().contains("content:")) {
                imagePath = getRealPathFromURI(targetUri);
            } else if (data.toString().contains("file:")) {
                imagePath = targetUri.getPath();
            } else {
                imagePath = null;
            }

 public String getRealPathFromURI(Uri contentUri) {
    Cursor cursor = null;
    try {
        String[] proj = {MediaStore.Images.Media.DATA};
        cursor = getContentResolver().query(contentUri, proj, null, null,
                null);
        int column_index = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}