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(){
public boolean accept(File f)
String fileNameInLower = f.getName().toLowerCase();
return (f.isFile() && (
fileNameInLower.endsWith(".jpg") ||
fileNameInLower.endsWith(".png") ||

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());


Popular posts from this blog

Space Character Problem on IE 6, 7, and 8

Does Netflix work on iOS 5 Beta 4?

AWS encryption chart (SSE-S3 vs SSE-KMS vs SSE-C)