如何从照片库中随机选择图像

时间:2014-02-15 21:46:50

标签: android image file

我需要从用户的照片库中随机选择一张图片。我并不是指在

中启动意图
Intent gallery = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(gallery, GALLERY_PHOTO_REQUEST_CODE);

没有。我需要自己随机选择图像。有没有一种有效的方法来做到这一点?或者我是否必须实际读入所有图像文件,然后随机选择一个文件,然后从文件中获取图像?通过阅读所有文件,我的意思是(片段:我有一个问题而不是答案)

void addFiles(final File parent, Set<File> images) {
        try {
            for (final File file : parent.listFiles()) {
                if (!file.getParent().contains("Android")) {

                    if (!file.isDirectory()) {
                        if (isImageFile(file.getName())) {
                            images.add(file);
                        }
                    } else {
                        addFiles(file, images);
                    }
                }
            }
        } catch (Exception e) {
        }
    }

请不要太在意代码段。如果我知道最好的方法,我就不会寻求帮助。有谁知道这样做的有效方法?

1 个答案:

答案 0 :(得分:0)

除了片段之外,我不知道你的代码。除非您拥有大量文件,否则您可以很好地将所有文件读入数组。然后生成一个随机数,其中0表示最低,arrayList.size() - 1表示最高,并从数组中获取该索引。

伪代码:

private static Random random = new Random();

ArrayList<File> list = readFiles();
File randomFile = list.get(getRandomValue(0, list.size()-1));
...

public static int getRandomValue(int low, int high) {

    return random.nextInt((high - low) + 1) + low;

}
相关问题