mediastore.mediacolumns.data已弃用,我想将图片从gallery加载到我的应用程序中

dced5bon  于 2021-08-20  发布在  Java
关注(0)|答案(5)|浏览(602)

我想使用mediastore.mediacolumns.data将galley中的所有图片加载到我的应用程序中,但不推荐使用。那么,加载它们的另一种方式是什么呢?
我现在使用此代码,但正如我所说的,它已被弃用:

fun getAllShownImagesPath(activity: Activity): MutableList<String> {
    val uri: Uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
    val cursor: Cursor?
    val columnIndexData: Int
    val listOfAllImages: MutableList<String> = mutableListOf()
    val projection = arrayOf(MediaStore.MediaColumns.DATA)
    var absolutePathOfImage: String
    cursor = activity.contentResolver.query(uri, projection, null, null, null)
    if (cursor != null) {
        columnIndexData = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA)
        while (cursor.moveToNext()) {
            absolutePathOfImage = cursor.getString(columnIndexData)
            listOfAllImages.add(absolutePathOfImage)
        }
        cursor.close()
    }
    return listOfAllImages
}
kzmpq1sx

kzmpq1sx1#

我能够用自己的文件id替换mediastore.mediacolumns.data(难以置信,文件有id),并正确构建其uri,如下所示:

fun getAllShownImagesPath(activity: Activity): MutableList<Uri> {
    val uriExternal: Uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
    val cursor: Cursor?
    val columnIndexID: Int
    val listOfAllImages: MutableList<Uri> = mutableListOf()
    val projection = arrayOf(MediaStore.Images.Media._ID)
    var imageId: Long
    cursor = activity.contentResolver.query(uriExternal, projection, null, null, null)
    if (cursor != null) {
        columnIndexID = cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID)
        while (cursor.moveToNext()) {
            imageId = cursor.getLong(columnIndexID)
            val uriImage = Uri.withAppendedPath(uriExternal, "" + imageId)
            listOfAllImages.add(uriImage)
        }
        cursor.close()
    }
    return listOfAllImages
}

然后使用uri在视图中构建它!

isr3a4wc

isr3a4wc2#

我设法想出了下面的解决方案,这是对前面答案的一种补充
但在那里,我仍然无法加载带有获取的uri的图像。文档建议我使用openfiledescriptor(),然后从中解码图像的位图:

override fun loadImagesFromStorage(): List<AdapterImage> {

    val uri: Uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
    val cursor: Cursor?
    val columnIndexId: Int
    val listOfAllImages = mutableListOf<AdapterImage>()
    val projection = arrayOf(MediaStore.Images.Media._ID)
    cursor = context.contentResolver
        .query( uri, projection, null, null, null)

    if ( cursor != null ){
        columnIndexId = cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID)
        while (cursor.moveToNext()){

            val contentUri = ContentUris.withAppendedId(uri, cursor.getLong(columnIndexId))

            //here I open FileDescriptor and then decode it into Bitmap
            var image: Bitmap
            context.contentResolver.openFileDescriptor(contentUri, "r").use { pfd ->
                if( pfd != null ){
                    image = BitmapFactory.decodeFileDescriptor(pfd.fileDescriptor)
                    listOfAllImages.add(AdapterImage(image))
                }
            }

        }
        cursor.close()
    }

    return listOfAllImages
}

p、 我的方法将返回我稍后在应用程序中使用的adapterimage对象列表,但此时您可以将任何需要的内容放在那个里

s5a0g9ez

s5a0g9ez3#

通过创建这个类,我最终解决了这个问题

class FileHelper {
val mediaType = "multipart/form-data".toMediaTypeOrNull()

fun getPartBodyFromUri(context: Context, uri: Uri): MultipartBody.Part {
    val realPath = getPathFromURI(context, uri)
    val fileImage = createFile(realPath)
    val requestBody = createRequestBody(fileImage)
    return createPart(fileImage, requestBody)
}

private fun createFile(realPath: String): File {
    return File(realPath)
}

private fun createRequestBody(file: File): RequestBody {
    return file.asRequestBody(mediaType)
}

private fun createPart(file: File, requestBody: RequestBody): MultipartBody.Part {
    return MultipartBody.Part.createFormData("imageFile", file.name, requestBody)
}

private fun getPathFromURI(context: Context, uri: Uri): String {
    var realPath = String()
    uri.path?.let { path ->

        val databaseUri: Uri
        val selection: String?
        val selectionArgs: Array<String>?
        if (path.contains("/document/image:")) { // files selected from "Documents"
            databaseUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
            selection = "_id=?"
            selectionArgs = arrayOf(DocumentsContract.getDocumentId(uri).split(":")[1])
        } else { // files selected from all other sources, especially on Samsung devices
            databaseUri = uri
            selection = null
            selectionArgs = null
        }
        try {
            val column = "_data"
            val projection = arrayOf(column)
            val cursor = context.contentResolver.query(
                databaseUri,
                projection,
                selection,
                selectionArgs,
                null
            )
            cursor?.let {
                if (it.moveToFirst()) {
                    val columnIndex = cursor.getColumnIndexOrThrow(column)
                    realPath = cursor.getString(columnIndex)
                }
                cursor.close()
            }
        } catch (e: Exception) {
            println(e)
        }
    }
    return realPath
}

}
media.data不推荐使用“mediastore.images.media.\u id”来获取正确的列,无法正常工作,因此我创建了所需的列

val column = "_data"
val projection = arrayOf(column)

然后我使用getcolumnindexorthrow()方法来获得正确的索引

val columnIndex = cursor.getColumnIndexOrThrow(column)
realPath = cursor.getString(columnIndex)
olmpazwi

olmpazwi4#

在 java

FileInputStream input = null;
    FileOutputStream output = null;
    try {
        String filePath = new File(getCacheDir(), "tmp").getAbsolutePath();
        android.os.ParcelFileDescriptor pfd = getContentResolver ().openFileDescriptor(
            sharedFileUri, "r");
        if (pfd != null) {
            FileDescriptor fd = pfd . getFileDescriptor ();
            input = new FileInputStream (fd);
            output = new FileOutputStream (filePath);
            int read;
            byte[] bytes = new byte[4096];
            while ((read = input.read(bytes)) != -1) {
                output.write(bytes, 0, read);
            }
            File sharedFile = new File(filePath);
            String finalPath = sharedFile.getPath();
        }
    }catch(Exception ex) {
    } finally {
        try {
            input.close();
            output.close();
        } catch (Exception ignored) {
        }
    }
8gsdolmq

8gsdolmq5#

正在从内部存储加载图像。正在使用mediastore类读取包含图像和视频的所有文件夹。
并将结果作为arraylist返回。

private fun getAllShownImagesPath(activity: Activity): ArrayList<Albums> {

val uri: Uri
val cursor: Cursor
var cursorBucket: Cursor
val column_index_data: Int
val column_index_folder_name: Int
val listOfAllImages = ArrayList<String>()
var absolutePathOfImage: String? = null
var albumsList = ArrayList<Albums>()
var album: Albums? = null

val BUCKET_GROUP_BY = "1) GROUP BY 1,(2"
val BUCKET_ORDER_BY = "MAX(datetaken) DESC"

uri = android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI

val projection = arrayOf(MediaStore.Images.ImageColumns.BUCKET_ID,
        MediaStore.Images.ImageColumns.BUCKET_DISPLAY_NAME,
        MediaStore.Images.ImageColumns.DATE_TAKEN,
        MediaStore.Images.ImageColumns.DATA)

cursor = activity.contentResolver.query(uri, projection, BUCKET_GROUP_BY, null, BUCKET_ORDER_BY)

if (cursor != null) {
    column_index_data = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA)
    column_index_folder_name = cursor
            .getColumnIndexOrThrow(MediaStore.Images.Media.BUCKET_DISPLAY_NAME)
    while (cursor.moveToNext()) {
        absolutePathOfImage = cursor.getString(column_index_data)
        Log.d("title_apps", "bucket name:" + cursor.getString(column_index_data))

        val selectionArgs = arrayOf("%" + cursor.getString(column_index_folder_name) + "%")
        val selection = MediaStore.Images.Media.DATA + " like ? "
        val projectionOnlyBucket = arrayOf(MediaStore.MediaColumns.DATA, MediaStore.Images.Media.BUCKET_DISPLAY_NAME)

        cursorBucket = activity.contentResolver.query(uri, projectionOnlyBucket, selection, selectionArgs, null)
        Log.d("title_apps", "bucket size:" + cursorBucket.count)

        if (absolutePathOfImage != "" && absolutePathOfImage != null) {
            listOfAllImages.add(absolutePathOfImage)
            albumsList.add(Albums(cursor.getString(column_index_folder_name), absolutePathOfImage, cursorBucket.count, false))
        }
    }
}
return getListOfVideoFolders(albumsList)
}

//此功能负责读取所有文件夹中的所有视频。

private fun getListOfVideoFolders(albumsList: ArrayList<Albums>): ArrayList<Albums> {
var cursor: Cursor
var cursorBucket: Cursor
var uri: Uri
val BUCKET_GROUP_BY = "1) GROUP BY 1,(2"
val BUCKET_ORDER_BY = "MAX(datetaken) DESC"
val column_index_album_name: Int
val column_index_album_video: Int

uri = android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI

val projection1 = arrayOf(MediaStore.Video.VideoColumns.BUCKET_ID,
        MediaStore.Video.VideoColumns.BUCKET_DISPLAY_NAME,
        MediaStore.Video.VideoColumns.DATE_TAKEN,
        MediaStore.Video.VideoColumns.DATA)

cursor = this.contentResolver.query(uri, projection1, BUCKET_GROUP_BY, null, BUCKET_ORDER_BY)

if (cursor != null) {
    column_index_album_name = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.BUCKET_DISPLAY_NAME)
    column_index_album_video = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA)
    while (cursor.moveToNext()) {
        Log.d("title_apps", "bucket video:" + cursor.getString(column_index_album_name))
        Log.d("title_apps", "bucket video:" + cursor.getString(column_index_album_video))
        val selectionArgs = arrayOf("%" + cursor.getString(column_index_album_name) + "%")

        val selection = MediaStore.Video.Media.DATA + " like ? "
        val projectionOnlyBucket = arrayOf(MediaStore.MediaColumns.DATA, MediaStore.Video.Media.BUCKET_DISPLAY_NAME)

        cursorBucket = this.contentResolver.query(uri, projectionOnlyBucket, selection, selectionArgs, null)
        Log.d("title_apps", "bucket size:" + cursorBucket.count)

        albumsList.add(Albums(cursor.getString(column_index_album_name), cursor.getString(column_index_album_video), cursorBucket.count, true))
    }
}
return albumsList
}

相关问题