当前位置: 首页 > 知识库问答 >
问题:

Android:如何在ImageView中获取位图的文件路径

慎旭尧
2023-03-14
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;
}

这是另一个:

public void uploadMultipart() {
    filePath = IndividualFragment.uri;
    String path = getPath(filePath);

    //Uploading code
    try {
        String uploadId = UUID.randomUUID().toString();

        //Creating a multi part request
        new MultipartUploadRequest(this, uploadId, Constants.UPLOAD_URL)
                .addFileToUpload(path, "image") //Adding file
                .addParameter("name", imgName) //Adding text parameter to the request
                .setNotificationConfig(new UploadNotificationConfig())
                .setMaxRetries(2)
                .startUpload(); //Starting the upload

    } catch (Exception exc) {
        Toast.makeText(this, exc.getMessage(), Toast.LENGTH_SHORT).show();
    }
}

另外,我在其他片段中使uri公共静态化,以便在MainActivity中可以访问,下面是将捕获的图像加载到ImageView的代码

@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    if (requestCode == REQUEST_IMAGE) {
        if (resultCode == Activity.RESULT_OK) {
            uri = data.getParcelableExtra("path");
            try {
                // You can update this bitmap to your server
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getActivity().getContentResolver(), uri);
                // loading profile image from local cache
                //loadProfile(uri.toString());
                imgProfile.setImageBitmap(bitmap);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

共有1个答案

左丘涵畅
2023-03-14

尝试以下代码:

如果您是在N+SDk中测试,请添加以下内容

创建xml/provider_paths.xml

<paths xmlns:android="http://schemas.android.com/apk/res/android">
   <external-path name="external_files" path="."/>
</paths>
<application>
...
<!-- Needed for Android >= Nougat for file access -->
  <provider
    android:name="android.support.v4.content.FileProvider"
    android:authorities="com.mypackage.myprovider"
    android:exported="false"
    android:grantUriPermissions="true">
   <meta-data
     android:name="android.support.FILE_PROVIDER_PATHS"
     android:resource="@xml/provider_paths"/>
  </provider>
...
</application>
     private void pickImage() {

    try {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        getActivity().startActivityForResult(Intent.createChooser(intent, "Pick Image"), 101);
    } catch (Exception ex) {
        ex.printStackTrace();
    }

}


@TargetApi(Build.VERSION_CODES.KITKAT)
private void captureImage() {
    try {

        if (getActivity().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            imageFilePath = getPathUri(getActivity());
            assert imageFilePath != null;
            manager.setLogoPath(imageFilePath.toString());
            if (imageFilePath != null) {
                intent.putExtra(MediaStore.EXTRA_OUTPUT, imageFilePath);
                getActivity().startActivityForResult(intent, 102);
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}




@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
  if (requestCode == 101) {
        if (resultCode == RESULT_OK) {
            try {

                Uri resultUri = data.getData();
                String path = getUriRealPath(getApplicationContext(), resultUri);
                File imgFile = new File(path);

                if (imgFile.exists()) {
                    Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
                    myBitmap = CommonMethods.scaleCenterCrop(myBitmap, 150, 150);
                    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                    myBitmap.compress(Bitmap.CompressFormat.PNG, 50, byteArrayOutputStream);
                    byte[] byteArray = byteArrayOutputStream.toByteArray();
                    String encoded = Base64.encodeToString(byteArray, Base64.DEFAULT);
                    application.getObserver().setLogoPath(encoded);
                }

            } catch (Exception ex) {
                ex.printStackTrace();
                DebugLog.e("ERROR => " + ex.getMessage());
            }


        }
    } else if (requestCode == 102) {

        if (resultCode == RESULT_OK) {
            if (data != null && data.getExtras() !=null){
                Bitmap imageBitmap = (Bitmap) data.getExtras().get("data");
                imageViewLogo.setImageBitmap(imageBitmap);
            } else {

                Uri uri = Uri.parse(manager.getLogoPath());
                try {
                    Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
                    bitmap = CommonMethods.scaleCenterCrop(bitmap, 150, 150);
                    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                    bitmap.compress(Bitmap.CompressFormat.PNG, 50, byteArrayOutputStream);
                    byte[] byteArray = byteArrayOutputStream .toByteArray();
                    String encoded = Base64.encodeToString(byteArray, Base64.DEFAULT);
                    application.getObserver().setLogoPath(encoded);
                    imageViewLogo.setImageBitmap(bitmap);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }

            }
        }
    }
}



@RequiresApi(api = Build.VERSION_CODES.KITKAT)
public static String getUriRealPath(Context ctx, Uri uri) {
    String ret = "";

    if (isAboveKitKat()) {
        // Android OS above sdk version 19.
        ret = getUriRealPathAboveKitkat(ctx, uri);
    } else {
        // Android OS below sdk version 19
        ret = getImageRealPath(ctx.getContentResolver(), uri, null);
    }

    return ret;
}


@RequiresApi(api = Build.VERSION_CODES.KITKAT)
private static String getUriRealPathAboveKitkat(Context ctx, Uri uri) {
    String ret = "";

    if (ctx != null && uri != null) {

        if (isContentUri(uri)) {
            if (isGooglePhotoDoc(uri.getAuthority())) {
                ret = uri.getLastPathSegment();
            } else {
                ret = getImageRealPath(ctx.getContentResolver(), uri, null);
            }
        } else if (isFileUri(uri)) {
            ret = uri.getPath();
        } else if (isDocumentUri(ctx, uri)) {

            // Get uri related document id.
            String documentId = DocumentsContract.getDocumentId(uri);

            // Get uri authority.
            String uriAuthority = uri.getAuthority();

            if (isMediaDoc(uriAuthority)) {
                String idArr[] = documentId.split(":");
                if (idArr.length == 2) {
                    // First item is document type.
                    String docType = idArr[0];

                    // Second item is document real id.
                    String realDocId = idArr[1];

                    // Get content uri by document type.
                    Uri mediaContentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                    if ("image".equals(docType)) {
                        mediaContentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                    } else if ("video".equals(docType)) {
                        mediaContentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                    } else if ("audio".equals(docType)) {
                        mediaContentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                    }

                    // Get where clause with real document id.
                    String whereClause = MediaStore.Images.Media._ID + " = " + realDocId;

                    ret = getImageRealPath(ctx.getContentResolver(), mediaContentUri, whereClause);
                }

            } else if (isDownloadDoc(uriAuthority)) {
                // Build download uri.
                Uri downloadUri = Uri.parse("content://downloads/public_downloads");

                // Append download document id at uri end.
                Uri downloadUriAppendId = ContentUris.withAppendedId(downloadUri, Long.valueOf(documentId));

                ret = getImageRealPath(ctx.getContentResolver(), downloadUriAppendId, null);

            } else if (isExternalStoreDoc(uriAuthority)) {
                String idArr[] = documentId.split(":");
                if (idArr.length == 2) {
                    String type = idArr[0];
                    String realDocId = idArr[1];

                    if ("primary".equalsIgnoreCase(type)) {
                        ret = Environment.getExternalStorageDirectory() + "/" + realDocId;
                    }
                }
            }
        }
    }

    return ret;
}


/* Check whether current android os version is bigger than kitkat or not. */
private static boolean isAboveKitKat() {
    boolean ret = false;
    ret = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
    return ret;
}

/* Check whether this uri represent a document or not. */
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
private static boolean isDocumentUri(Context ctx, Uri uri) {
    boolean ret = false;
    boolean ver = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
    if (ctx != null && uri != null) {
        if (ver) {
            ret = DocumentsContract.isDocumentUri(ctx, uri);
        }
    }
    return ret;
}

/* Check whether this uri is a content uri or not.
 *  content uri like content://media/external/images/media/1302716
 *  */
private static boolean isContentUri(Uri uri) {
    boolean ret = false;
    if (uri != null) {
        String uriSchema = uri.getScheme();
        if ("content".equalsIgnoreCase(uriSchema)) {
            ret = true;
        }
    }
    return ret;
}

/* Check whether this uri is a file uri or not.
 *  file uri like file:///storage/41B7-12F1/DCIM/Camera/IMG_20180211_095139.jpg
 * */
private static boolean isFileUri(Uri uri) {
    boolean ret = false;
    if (uri != null) {
        String uriSchema = uri.getScheme();
        if ("file".equalsIgnoreCase(uriSchema)) {
            ret = true;
        }
    }
    return ret;
}


/* Check whether this document is provided by ExternalStorageProvider. */
private static boolean isExternalStoreDoc(String uriAuthority) {
    boolean ret = false;

    if ("com.android.externalstorage.documents".equals(uriAuthority)) {
        ret = true;
    }

    return ret;
}

/* Check whether this document is provided by DownloadsProvider. */
private static boolean isDownloadDoc(String uriAuthority) {
    boolean ret = false;

    if ("com.android.providers.downloads.documents".equals(uriAuthority)) {
        ret = true;
    }

    return ret;
}

/* Check whether this document is provided by MediaProvider. */
private static boolean isMediaDoc(String uriAuthority) {
    boolean ret = false;

    if ("com.android.providers.media.documents".equals(uriAuthority)) {
        ret = true;
    }

    return ret;
}

/* Check whether this document is provided by google photos. */
private static boolean isGooglePhotoDoc(String uriAuthority) {
    boolean ret = false;

    if ("com.google.android.apps.photos.content".equals(uriAuthority)) {
        ret = true;
    }
    return ret;
}

/* Return uri represented document file real local path.*/
private static String getImageRealPath(ContentResolver contentResolver, Uri uri, String whereClause) {
    String ret = "";

    // Query the uri with condition.
    Cursor cursor = contentResolver.query(uri, null, whereClause, null, null);

    if (cursor != null) {
        boolean moveToFirst = cursor.moveToFirst();
        if (moveToFirst) {

            // Get columns name by uri type.
            String columnName = MediaStore.Images.Media.DATA;

            if (uri == MediaStore.Images.Media.EXTERNAL_CONTENT_URI) {
                columnName = MediaStore.Images.Media.DATA;
            } else if (uri == MediaStore.Audio.Media.EXTERNAL_CONTENT_URI) {
                columnName = MediaStore.Audio.Media.DATA;
            } else if (uri == MediaStore.Video.Media.EXTERNAL_CONTENT_URI) {
                columnName = MediaStore.Video.Media.DATA;
            }

            // Get column index.
            int imageColumnIndex = cursor.getColumnIndex(columnName);

            // Get column value which is the uri related file local path.
            ret = cursor.getString(imageColumnIndex);
        }
    }

    return ret;
}


 public static Uri getPathUri(Context context) {
        try {
            String strDate = (new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US)).format(new Date());
            File fileDirectory = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "APP");
            if (!fileDirectory.exists()) {
                if (!fileDirectory.mkdirs()) {
                    DebugLog.e("Oops! Failed create : \n" + "APP" + " directory");
                }
            }
            File f = new File(fileDirectory.getPath() + File.separator, "IMG_" + strDate + ".jpeg");

            if (Build.VERSION.SDK_INT >= 24) {
                return FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".provider", f);
            } else {
                return Uri.fromFile(f);
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }
 类似资料:
  • 我想从SD卡文件路径中获取文件名。e、 g.:/storage/sdcard0/DCIM/Camera/1414240995236。jpg我想得到1414240995236。jpg我已经编写了获取相同内容的代码,但它不起作用。请帮忙<下面是我的代码:

  • 我正试图在我的Android应用程序中导入sky.csv文件。 请帮我做这个。我试过这么多方法。然而,我没有得到任何适当的解决办法。

  • 问题内容: 我有一个可以制作图片并上传图片的应用。上载需要照片的文件路径,但无法获取。 这是我的代码: 请帮助我获取文件路径。 谢谢 问题答案: 发布到Twitter时,需要在发布请求中发送图片在设备上的实际路径。我发现很难找到实际的路径,而且经常会发现错误的路径。 为了解决这个问题,一旦有了a ,我就可以使用来获取。随后,我使用实例获取设备上的实际路径。 这是生产代码,并且经过了自然测试。;-)

  • 我正在开发一个Android应用程序。它有一个功能,捕获的图像应该显示在屏幕上,我需要得到那个图像路径,这样我就可以把那个图像发送到服务器。 我可以在屏幕上显示图像,但无法获得绝对图像路径。 我得到的路径像: 如何获取实际图像路径? 这是我的密码: 值如上所示。 我如何从这个路径得到我的绝对图像路径。

  • 我正在创建一个应用程序,从画廊上传选定的图像,并上传到一个网络服务。web服务需要所选图像的文件名以及文件内容的base64编码。我已经设法用硬编码的文件路径实现了这一点。然而,我很难获得图像的真实文件路径。我在网上看了很多资料,找到了这段代码,但它对我不起作用: 我得到这个错误: 编辑 忘了提到我正在使用Kitkat。看起来我的问题与KitKat有关。我发现了这个(见下文),它帮助我让我的应用程

  • 我正在开发一个聊天应用程序,它确实需要显示与我聊天的每个人的个人资料图片。如果是一个群组对话,我需要设计一个类似于的布局,如下所示 我正在考虑使用实现它,但不确定如何实现。此外,还需要从加载映像。我正在使用Glide库加载。