Get/pick an image from Android's built-in Gallery app programmatically

前端 未结 19 1158
终归单人心
终归单人心 2020-11-22 00:49

I am trying to open an image / picture in the Gallery built-in app from inside my application.

I have a URI of the picture (the picture is located on the SD card).

19条回答
  •  长情又很酷
    2020-11-22 01:06

    Additional to previous answers, if you are having problems with getting the right path(like AndroZip) you can use this:

      public String getPath(Uri uri ,ContentResolver contentResolver) {
            String[] projection = {  MediaStore.MediaColumns.DATA};
            Cursor cursor;
            try{
                cursor = contentResolver.query(uri, projection, null, null, null);
            } catch (SecurityException e){
                String path = uri.getPath();
                String result = tryToGetStoragePath(path);
                return  result;
            }
            if(cursor != null) {
                //HERE YOU WILL GET A NULLPOINTER IF CURSOR IS NULL
                //THIS CAN BE, IF YOU USED OI FILE MANAGER FOR PICKING THE MEDIA
                cursor.moveToFirst();
                int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
                String filePath = cursor.getString(columnIndex);
                cursor.close();
                return filePath;
            }
            else
                return uri.getPath();               // FOR OI/ASTRO/Dropbox etc
        }
    
        private String tryToGetStoragePath(String path) {
            int actualPathStart = path.indexOf("//storage");
            String result = path;
    
            if(actualPathStart!= -1 && actualPathStart< path.length())
                result = path.substring(actualPathStart+1 , path.length());
    
            return result;
        }
    

提交回复
热议问题