如何从存储在SD卡上的图像中获取图像路径

时间:2010-10-06 14:23:41

标签: android

是否可以获取存储在我的Android手机的SD卡上的所有图像的路径?还可以检查存储在SD卡或内部存储器中的其他图像吗?我目前正在这样做:

Cursor cur = this.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, null, null,null);  
        startManagingCursor(cur);  
        cur.moveToFirst();
        while (cur.moveToNext()) {
            String str = cur.getString(cur.getColumnIndex(MediaStore.Images.ImageColumns.BUCKET_DISPLAY_NAME));
            Log.e("#########",str);
        }

这似乎就像返回目录名一样, 我也见过这段代码:

File images = Environment.getDataDirectory();  
        File[] imagelist = images.listFiles(new FilenameFilter(){  
        public boolean accept(File dir, String name)  
        {  
            return ((name.endsWith(".jpg"))||(name.endsWith(".png")));  
        }  
    });  
        String []mFiles = new String[imagelist.length];  

        for(int i= 0 ; i< imagelist.length; i++)  
        {  
            mFiles[i] = imagelist[i].getAbsolutePath();  
        }  
        Uri[] mUrls = new Uri[mFiles.length];  

        for(int i=0; i < mFiles.length; i++)  
        {  
            mUrls[i] = Uri.parse(mFiles[i]);  
            Log.e("###############","MURIS: "+mUrls[i].getEncodedPath());
        }     

但是这会抛出一个nullpointer异常。

1 个答案:

答案 0 :(得分:4)

您可以使用FileFilter。这是我写的一个用于返回包含图像的目录列表。从这里,修改它以返回图像列表应该相当简单:

FileFilter filterForImageFolders = new FileFilter() 
    {            
        public boolean accept(File folder) 
        { 
            try 
            { 
                //Checking only directories, since we are checking for files within 
                //a directory 
                if(folder.isDirectory()) 
                { 
                    File[] listOfFiles = folder.listFiles(); 

                    if (listOfFiles == null) return false; 

                    //For each file in the directory... 
                    for (File file : listOfFiles) 
                    {                            
                        //Check if the extension is one of the supported filetypes                           
                        //imageExtensions is a String[] containing image filetypes (e.g. "png")
                        for (String ext : imageExtensions) 
                        { 
                            if (file.getName().endsWith("." + ext)) return true; 
                        } 
                    }                        
                } 
                return false; 
            } 
            catch (SecurityException e) 
            { 
                Log.v("debug", "Access Denied"); 
                return false; 
            } 
        } 
    };

编辑:澄清一下,使用它,你会做类似下面的事情:

File extStore = Environment.getExternalStorageDirectory();
File[] imageDirs = extStore.listFiles(filterForImageFolders);