【问题标题】:How to list images from a specific folder如何列出特定文件夹中的图像
【发布时间】:2021-09-04 06:33:45
【问题描述】:

你好吗?

我正在构建一个在 recyclerview 上显示图像的应用。 感谢教程,我设法从外部存储加载所有图像,但接下来我想做的是从特定目录加载图像,例如 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()
    }
}

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

【问题讨论】:

  • and to load images from external storage 没有加载任何内容。您正在尝试从 MediaStore 中的相对 parh 中列出图像。乍一看,您的代码看起来不错。
  • 所用设备的安卓版本是多少?
  • @blackapps 我用的是android 11。当我没有用目录查询时它工作了
  • “查询目录”是什么意思?请准确。请换个话题。您正在使用相对路径查询媒体存储。添加mediastore 标签。移除外部存储标签。
  • 添加标签,谢谢。选择为null时已成功列出图像。所以我以为是因为Selection中插入的目录。对不起,如果我让你感到困惑。

标签: android kotlin mediastore


【解决方案1】:

尝试使用以下功能: 首先用你要搜索的文件夹的名称声明一个 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
            }

        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-14
    • 2011-03-28
    • 2016-10-03
    • 1970-01-01
    • 2015-04-02
    • 2018-12-02
    相关资源
    最近更新 更多