简体   繁体   English

如何找到android图像的路径并从Uri创建文件

[英]How to find path to android image and create File from Uri

I have a problem with converting Uri path to URI(to create a file).我在将 Uri 路径转换为 ​​URI(以创建文件)时遇到问题。

My code is:我的代码是:

private void uploadImageToServer(Uri path){
    String[] filePathColumn = {MediaStore.Images.Media.DATA};

    android.database.Cursor cursor = getContentResolver().query(path, filePathColumn, null, null, null);
    if (cursor == null)
        return;

    cursor.moveToFirst();

    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
    String filePath = cursor.getString(columnIndex);
    cursor.close();

    File file = new File(filePath);
}

However my cursor is null.但是我的光标为空。

My "Uri path" parameter from function is: file:///storage/emulated/0/Pictures/MyApp/IMG_20170411_170952.jpg我的“Uri 路径”参数是: file:///storage/emulated/0/Pictures/MyApp/IMG_20170411_170952.jpg

I was following this tutorial: https://medium.com/@adinugroho/upload-image-from-android-app-using-retrofit-2-ae6f922b184c我正在关注本教程: https : //medium.com/@adinugroho/upload-image-from-android-app-using-retrofit-2-ae6f922b184c

try this and and I highly recommend not using试试这个,我强烈建议不要使用

content:// 

just use it as只需将其用作

content:

String imagePath = "";
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();
        }
    }
}
My "Uri path" parameter from function is: 
file:///storage/emulated/0/Pictures/MyApp/IMG_20170411_170952.jpg

Then the path you are after is那么你所追求的路径是

/storage/emulated/0/Pictures/MyApp/IMG_20170411_170952.jpg

Code代码

private void uploadImageToServer(Uri uri){
   String filePath = uri.toString().replace("file://", "" );

   File file = new File(filePath);
}

Maybe you could even use uri.getPath() directly.也许你甚至可以直接使用 uri.getPath() 。 Please check.请检查。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM