Skip to content

Incorrect calculateInSampleSize leads to overly degraded quality #152

@FlorianDenis

Description

@FlorianDenis

You have an issue in calculateInSampleSize where the return results does not match the comment "largest value that keeps both height and width larger than the requested height and width".

For instance for an image of size 3000x3000, if the requested size is 2000x2000, your code returns inSampleSize = 2, leading to a 1500x1500 overly degraded image being loaded in memory and then upscaled to 2000x2000

Here follows my suggestion for correction, but feel free to adapt however you want

fun calculateInSampleSize(
    options: BitmapFactory.Options,
    reqWidth: Int,
    reqHeight: Int
): Int {
    // Raw height and width of image
    var height = options.outHeight
    var width = options.outWidth
    var sampleSize = 1

    // Calculate the largest inSampleSize value that is a power of 2 and keeps both
    // height and width larger than the requested height and width.
    while(height / 2 > reqHeight || width / 2 > reqWidth) {
        sampleSize *= 2
        height /= 2
        width /= 2
    }

    return sampleSize
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions