Pick random image from a given directory

I have created a new method in order grab a random image from a directory.
Since Android's image types are specified in SDK, our method returns ".jpg", ".png"(9.png also included), ".gif"(not recommended).

private Bitmap getRandomImage(String pDirectory)
{
// Get only the image files.(.png-preferred, .jpg-acceptable, .gif-discouraged)
FileFilter imageFileFilter = new FileFilter(){
@Override
public boolean accept(File f)
{
String fileNameInLower = f.getName().toLowerCase();
return (f.isFile() && (
fileNameInLower.endsWith(".jpg") ||
fileNameInLower.endsWith(".png") ||
fileNameInLower.endsWith(".gif")));
}
};

File[] imageFileArray = new File(pDirectory).listFiles(imageFileFilter);
if(imageFileArray == null)
{ // No appropriate file found in the directory.
return null;
}

// Choose one random image from the file array.
Random randomImageGenerator = new Random(System.currentTimeMillis());
int randomImageIndex = randomImageGenerator.nextInt(imageFileArray .length);

return BitmapFactory.decodeFile(imageFileArray[randomImageIndex].getAbsolutePath());
}

Comments

Popular posts from this blog

Configure hosts File in Android

Is Wharton Business Foundations Specialization Good?

iTunes cannot restore the iPhone because Find My iPhone is on and applications are gone!