【问题标题】:Displaying all images from device in my app在我的应用程序中显示来自设备的所有图像
【发布时间】:2015-08-26 22:13:45
【问题描述】:

我正在使用下面的代码从 DCIM 内的 Camera 文件夹中获取所有图像并显示在我的应用程序中。但我想在我的应用程序中显示设备上的所有图像,无论它们存储在设备上的什么位置。我该怎么做?

 String ExternalStorageDirectoryPath = Environment
                .getExternalStorageDirectory()
                .getAbsolutePath();
        String targetPath = ExternalStorageDirectoryPath + "/DCIM/Camera";
        images=new ArrayList<String>();
        File targetDirector = new File(targetPath);

        File[] files = targetDirector.listFiles();
        for (File file : files) {

            images.add(file.getAbsolutePath());
        }
        gallerylist=new CameraGalleryAdapter(getActivity().getApplicationContext(),R.layout.giphy_grid,images);
        gridview.setAdapter(gallerylist);

【问题讨论】:

标签: android android-camera android-gallery android-external-storage


【解决方案1】:

首先检查是否授予了所需的权限:

if (ActivityCompat.checkSelfPermission(CurrentActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
     ActivityCompat.requestPermissions(CurrentActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, PICK_FROM_GALLERY)
}

然后你必须检查SD卡是否可用:

Boolean isSDPresent = android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);

如果存在 SD 卡,则使用此卡:

final String[] columns = { MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID };
final String orderBy = MediaStore.Images.Media._ID;
//Stores all the images from the gallery in Cursor
Cursor cursor = getContentResolver().query(
        MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null,
        null, orderBy);
//Total number of images
int count = cursor.getCount();

//Create an array to store path to all the images
String[] arrPath = new String[count];

for (int i = 0; i < count; i++) {
    cursor.moveToPosition(i);
    int dataColumnIndex = cursor.getColumnIndex(MediaStore.Images.Media.DATA);
    //Store the path of the image
    arrPath[i]= cursor.getString(dataColumnIndex);
    Log.i("PATH", arrPath[i]);
}
// The cursor should be freed up after use with close()
cursor.close();

上面的代码将列出所有来自 SD 卡的图像,如果要从内存中获取图像,只需替换

MediaStore.Images.Media.EXTERNAL_CONTENT_URI

MediaStore.Images.Media.INTERNAL_CONTENT_URI

使用相同的 sn-p 代码。

【讨论】:

  • 仅获取所有“照片”图像的最佳做法是什么?目前我直接从 DCIM 文件夹中列出文件,然后获取路径,但我想知道是否有最佳实践。
  • @HendraWijayaDjiono 没有“常见的最佳实践”。如果您注意到在 Marshmallow 设备上获取图像的方式不再一致。请发布一个单独的问题,或者也许有人已经有。然后告诉我,我会把我的 2 美分放进去。
  • 不适用于 5.0。请再次查看它需要一些帮助:)
  • @zaeemsattar 是的,它现在可能无法正常工作,而且这个答案可能已经过时,感谢您的评论,我会更新它。
  • @SharpEdge 谢谢
猜你喜欢
  • 2019-04-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-22
  • 1970-01-01
  • 2023-01-02
  • 1970-01-01
  • 2022-06-14
相关资源
最近更新 更多