【问题标题】:How do I randomly select an image from photo gallery如何从照片库中随机选择图像
【发布时间】:2014-02-15 21:46:50
【问题描述】:

我需要从用户的照片库中随机选择一张图片。我的意思不是像

那样开始一个意图
Intent gallery = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(gallery, GALLERY_PHOTO_REQUEST_CODE);

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

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) {
        }
    }

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

【问题讨论】:

    标签: android image file


    【解决方案1】:

    除了sn-ps,我不知道你的代码。除非您有大量文件,否则您可以很好地将所有文件读入一个数组。然后生成一个随机数,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;
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-05
      • 1970-01-01
      • 2013-07-10
      • 2012-03-21
      • 2017-09-06
      • 2012-03-06
      • 2016-07-04
      • 2016-07-13
      相关资源
      最近更新 更多