Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Content resolver returns wrong size

I am picking an image from the gallery and querying its size via ContentResolver API, it returns 29kb.

However when I check the file via adb using ls -al it is 44kb

here is how I query the size of the image:

    private fun getFileInfo(contentResolver: ContentResolver, fileUri: Uri): Pair<String, Long>? {
    val projection = arrayOf(MediaStore.MediaColumns.DISPLAY_NAME, MediaStore.MediaColumns.SIZE)
    val metaCursor = contentResolver.query(fileUri, projection, null, null, null)
        metaCursor?.use {
            if (it.moveToFirst()) {
                val displayNameIndex = it.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME)
                val sizeIndex = it.getColumnIndex(MediaStore.MediaColumns.SIZE)
                return Pair(it.getString(displayNameIndex), it.getLong(sizeIndex))
            }
    }
    return null
}

I am using an Oreo Emulator. I have also checked via emulator's tools, file browser shows as 29kb on the other hand file details shows 45kb. What is going on?

Here are the images from file browser:

Summary

Details

Another side note, above situation can be reproducible every time when using camera app on emulator with Android 26-Oreo emulator, however it is fine with emulator Android 25-Nougat.

I have checked, new Document API also returns 29kb

like image 657
guness Avatar asked Jan 17 '18 14:01

guness


1 Answers

I had a similar issue. The ContentResolver was underestimating the true filesize by about 400 bytes. I solved it using a similar approach to that explained in How to correctly get the file size of an android.net.Uri? :

ParcelFileDescriptor pfd = getContentResolver().openFileDescriptor(imageUri, "r");
fileLength = pfd.getStatSize();
pfd.close();
like image 69
Slim Jimmy Avatar answered Sep 19 '22 00:09

Slim Jimmy