Images from folder on sd card

后端 未结 1 485
我在风中等你
我在风中等你 2021-02-06 16:24

I have an application that needs to read images from a folder created by the application on the sdcard(sdcard/\"foldername\"/\"filename.jpg\". I have no idea what the names of t

相关标签:
1条回答
  • 2021-02-06 16:50

    Here's how you can get a list of folders off of the memory card:

    String state = Environment.getExternalStorageState();
    if(state.contentEquals(Environment.MEDIA_MOUNTED) || state.contentEquals(Environment.MEDIA_MOUNTED_READ_ONLY)) 
    {
        String homeDir = Environment.getExternalStorageDirectory();
        File file = new File(homeDir);
        File[] directories = file.listFiles();
    } 
    else 
    {
        Log.v("Error", "External Storage Unaccessible: " + state);
    }
    

    This code is from the top of my head, so some syntax may be off a bit, but the general idea should work. You can use something like this to filter down the folders to only folders that contain images:

    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; 
                } 
            } 
        };
    

    Then, change the first example to:

    File[] directories = file.listFiles(filterForImageFolders);

    That should return only directories that contain images. Hopefully this helps some!

    0 讨论(0)
提交回复
热议问题