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

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

Is Wharton Business Foundations Specialization Good?

Sending Large Data with JSON