如何列出特定文件夹中的图像

How to list images from a specific folder

你好吗?

我正在构建一个在回收站视图上显示图像的应用程序。 多亏了一个教程,我设法从外部存储加载所有图像,但我接下来要做的是从特定目录加载图像,例如 Pictures/TestApp。 为了将图像保存在目录中,我使用了这段代码,

private fun saveMediaToStorage(bitmap: Bitmap) {
    val filename = "${System.currentTimeMillis()}.jpg"

    var fos: OutputStream? = null


    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        // getting the contentResolver
        this.contentResolver?.also { resolver ->


            val contentValues = ContentValues().apply {


                put(MediaStore.MediaColumns.DISPLAY_NAME, filename)
                put(MediaStore.MediaColumns.MIME_TYPE, "image/jpg")
                put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_PICTURES+ File.separator + "TestApp")
                put(MediaStore.Images.Media.WIDTH, bitmap.width)
                put(MediaStore.Images.Media.HEIGHT, bitmap.height)
            }

            val imageUri: Uri? = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues)

            fos = imageUri?.let { resolver.openOutputStream(it) }
        }
    } else {

        val imagesDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES+ File.separator + "TestApp")
        val image = File(imagesDir, filename)
        fos = FileOutputStream(image)
    }

    fos?.use {
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, it)
        Toast.makeText(this, "saved the image", Toast.LENGTH_SHORT).show()
    }
}

并从外部存储加载图像,

private suspend fun loadPhotosFromExternalStorage(): List<UserWork> {
    return withContext(Dispatchers.IO) {
        val collection = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
        val path = "Pictures/TestApp%"
        val selection = "${MediaStore.MediaColumns.RELATIVE_PATH} LIKE ?"
        val selectionargs = arrayOf(path)

        val projection = arrayOf(
            MediaStore.Images.Media._ID,
            MediaStore.Images.Media.DISPLAY_NAME
        )
        val photos = mutableListOf<UserWork>()

        requireActivity().contentResolver.query(
            collection,
            projection,
            selection,
            selectionargs,
            "${MediaStore.Images.Media.DISPLAY_NAME} DESC"
        )?.use { cursor ->
            val idColumn = cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID)
            val displayNameColumn = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DISPLAY_NAME)


            while (cursor.moveToNext()) {
                val id = cursor.getLong(idColumn)
                val displayName = cursor.getString(displayNameColumn)
                val contentUri = ContentUris.withAppendedId(
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                    id
                )
                photos.add(UserWork(id, displayName, contentUri))
            }
            photos.toList()
        } ?: listOf()
    }
}

我进行了调试,但在该目录中没有找到任何图像。 如果您能解释为什么这不起作用,我将不胜感激!

尝试使用以下函数实现相同的目的: 首先用要搜索的文件夹的名称声明一个 const 变量:

const val TESTAPP = "TestApp"

然后使用下面的函数获取数据

override suspend fun getData(): List<UserWork>? =

        withContext(Dispatchers.IO) {
            try {

                val collection = if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                    MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL)
                } ?: MediaStore.Images.Media.EXTERNAL_CONTENT_URI

                val selection =
                    MediaStore.Images.ImageColumns.RELATIVE_PATH + " like ? "
                val projection = arrayOf(
                    MediaStore.Images.Media._ID,
                    MediaStore.Images.Media.DISPLAY_NAME,
                    MediaStore.Images.Media.RELATIVE_PATH,
                    MediaStore.Images.Media.BUCKET_DISPLAY_NAME,
                    MediaStore.Images.Media.BUCKET_ID,
                    MediaStore.MediaColumns.WIDTH
                )

                val selectionArgs = arrayOf("%$TESTAPP%")

                val sortOrder = MediaStore.MediaColumns.DATE_ADDED + " COLLATE NOCASE DESC"

                val itemList: MutableList<UserWork> = mutableListOf()

                context.contentResolver?.query(
                    collection,
                    projection,
                    selection,
                    selectionArgs,
                    sortOrder
                )?.use { cursor ->

                    val idColumn = cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID)
                    val displayNameColumn =
                        cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DISPLAY_NAME)
                    val relativePathColumn =
                        cursor.getColumnIndexOrThrow(MediaStore.Images.Media.RELATIVE_PATH)
                    val widthPathColumn =
                        cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.WIDTH)


                    while (cursor.moveToNext()) {
                        val id = cursor.getLong(idColumn)
                        val displayName = cursor.getString(displayNameColumn)
                        val relativePath = cursor.getString(relativePathColumn)
                        val width = cursor.getInt(widthPathColumn)


                        val contentUri = ContentUris.withAppendedId(
                            MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                            id
                        )

                        itemList.add(UserWork(id, displayName, contentUri))
         
                    }
                    cursor.close()
                }

                itemList
            } catch (e: Exception) {
                Log.d(
                    "MediaStoreException", "The exception for getData is " +
                            "$e"
                )
                null
            }

        }