Resize a large bitmap file to scaled output file on Android

前端 未结 21 935
执念已碎
执念已碎 2020-11-22 05:51

I have a large bitmap (say 3888x2592) in a file. Now, I want to resize that bitmap to 800x533 and save it to another file. I normally would scale the bitmap by calling

21条回答
  •  广开言路
    2020-11-22 06:13

    I use Integer.numberOfLeadingZeros to calculate the best sample size, better performance.

    Full code in kotlin:

    @Throws(IOException::class)
    fun File.decodeBitmap(options: BitmapFactory.Options): Bitmap? {
        return inputStream().use {
            BitmapFactory.decodeStream(it, null, options)
        }
    }
    
    @Throws(IOException::class)
    fun File.decodeBitmapAtLeast(
            @androidx.annotation.IntRange(from = 1) width: Int,
            @androidx.annotation.IntRange(from = 1) height: Int
    ): Bitmap? {
        val options = BitmapFactory.Options()
    
        options.inJustDecodeBounds = true
        decodeBitmap(options)
    
        val ow = options.outWidth
        val oh = options.outHeight
    
        if (ow == -1 || oh == -1) return null
    
        val w = ow / width
        val h = oh / height
    
        if (w > 1 && h > 1) {
            val p = 31 - maxOf(Integer.numberOfLeadingZeros(w), Integer.numberOfLeadingZeros(h))
            options.inSampleSize = 1 shl maxOf(0, p)
        }
        options.inJustDecodeBounds = false
        return decodeBitmap(options)
    }
    

提交回复
热议问题