Search code examples
androidandroid-contentresolver

Getting photo dimension of locally stored photo


I'd like to know photos width and height before loading a bitmap. I'm using latest approach of ContentResolver to query locally stored photos.

        contentResolver.query(
            collection,
            projection,
            selection,
            selectionArgs,
            sortOrder
        )!!.use { cursor ->
            while (cursor.moveToNext()) {
                // Use an ID column from the projection to get
                // a URI representing the media item itself.
                val idColumn = cursor.getColumnIndex(MediaStore.Images.Media._ID)
                val widthColumn = cursor.getColumnIndex(MediaStore.Images.Media.WIDTH)

                val id: Long = cursor.getLong(idColumn)
                val width: Int = cursor.getInt(widthColumn) //CRASH                    
            }

Cursor is crashing on the selected line width:

IllegalStateException: Couldn't read row 0, col -1 from CursorWindow.  Make sure the Cursor is initialized correctly before accessing data from it.

How am I supposed to do that then?


Solution

  • Try This

    val projection = arrayOf(
                MediaStore.Images.Media._ID,
                MediaStore.Images.Media.WIDTH,
                MediaStore.Images.Media.HEIGHT
            )
    
            val images: Uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
            contentResolver.query(
                images,
                projection,
                null,
                null,
                null
            )!!.use { cursor ->
                if (cursor.count > 0) {
                    val idColumn = cursor.getColumnIndex(MediaStore.Images.Media._ID)
                    val widthColumn = cursor.getColumnIndex(MediaStore.Images.Media.WIDTH)
                    val heightColumn = cursor.getColumnIndex(MediaStore.Images.Media.HEIGHT)
    
                    while (cursor.moveToNext()) {
                        val id: Long = cursor.getLong(idColumn)
                        val width: Int = cursor.getInt(widthColumn)
                        val height: Int = cursor.getInt(heightColumn)
                        Log.e("tag", " width :: $width - height :: $height");
                    }
                }
            }