简体   繁体   中英

while selecting image from gallery image path is not returned in android

Hi I'm selecting the image from gallery in emulator. When I click the browse button and select the image, I have written the code to retrieve the path of the image. But it is not displayed. When I use Log to print the path in the logcat, it displays error. Please help me out to display the image path. This is my code.


public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK) {
        if (requestCode == SELECT_PICTURE) {
            Uri selectedImageUri = data.getData();
            selectedImagePath = getPath(selectedImageUri);
           logo_path.setText(selectedImagePath);

        }
    }
}
public String getPath(Uri uri) {
    String[] projection = { MediaStore.Images.Media.DATA };
    Cursor cursor = managedQuery(uri, projection, null, null, null);
    int column_index = cursor
            .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);
}

Try this.

public String getImagePathFromURI(Uri uri) {

    String imgpath = "";
    Cursor c= getContentResolver().query(uri, null, null, null, null);

    if (c == null) { 

        imgpath= uri.getPath();  // Getting path from url itself

    } else { 

        c.moveToFirst();
        int id = c.getColumnIndex(MediaStore.Images.ImageColumns.DATA); 
        result = c.getString(id);
        c.close();  // Close curson.
    }

    return imgpath;  // original image path
}
public String getRealPathFromURI(Uri contentUri) {
    String[] proj = { MediaStore.Images.Media.DATA };
    @SuppressWarnings("deprecation")
    Cursor cursor = managedQuery(contentUri, proj, null, null, null);
    if (cursor == null)
        return null;
    int column_index = cursor
            .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);
}

and in your onActivityResult use

String path = getRealPathFromURI(uri); 
Bitmap bmp = BitmapFactory.decodeFile(path); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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