HavanaSun
HavanaSun

Reputation: 936

Resizing bitmap makes quality way worse

I'm using this simple function to scale my bitmaps to the same size:

fun resizeImage(file: File) {

    val resized = BitmapFactory.decodeFile(file.absolutePath)
  
    if (resized != null) {
        val resizedBitmap = Bitmap.createScaledBitmap(
            resized, 512, 512, false
        )
        file.outputStream().use {
            resizedBitmap.compress(Bitmap.CompressFormat.WEBP, 100, it)
            resizedBitmap.recycle()
        }
    }
}

Using this function makes the image quality visibly worse, before the images have an resolution of 480x480, scaling them with this function makes the quality like 40% worse.

I got the quality put on 100, what else can I do?

Upvotes: 0

Views: 163

Answers (2)

cactustictacs
cactustictacs

Reputation: 19524

You're not using filtering when you call createScaledBitmap (the last parameter). From the docs:

filter boolean: Whether or not bilinear filtering should be used when scaling the bitmap. If this is true then bilinear filtering will be used when scaling which has better image quality at the cost of worse performance. If this is false then nearest-neighbor scaling is used instead which will have worse image quality but is faster. Recommended default is to set filter to 'true' as the cost of bilinear filtering is typically minimal and the improved image quality is significant.

Nearest-neighbour scaling basically enlarges your image by duplicating some pixels to fill the extra space, instead of smoothly blending between them. So you get this blocky look - which can be a good thing for pixel art, not so much for photos etc.

The other issue is you're scaling by a weird amount, 480 to 512 which is 1.0666667 times as many pixels. Bilinear filtering can handle that and blend the original pixels across that larger range. But nearest-neighbour can't duplicate pixels evenly in that situation. Round numbers like 2x and 3x work fine - every pixel becomes two or whatever. But if you have 480 and you need to add another 32 - some will get duplicated, some won't. ABCDEF becomes AABCCDEEF, that kind of thing. It'll probably look pretty bad and distorted, as well as being blocky

Upvotes: 1

Dave The Dane
Dave The Dane

Reputation: 869

Try using Thumbnailator, it's the best quality you'll find.

https://github.com/coobird/thumbnailator

https://mvnrepository.com/artifact/net.coobird/thumbnailator

P.S. Hmmm...
...flew over your posting too quickly maybe.
I guess that won't be available on Android, but I'll let it stand just in case it's of interest.

Upvotes: 0

Related Questions