androidkotlinbitmapandroid-bitmap

Split big bitmap to list of bitmaps in android


I have a big bitmap - sometimes with height 2000 sometimes 4000 etc. This is possible to split this big bitmap dividing by 1500 and save into array?

For example if I have bitmap with height 2300 I want to have array with two bitmaps: one 1500 height and second 800.


Solution

  • You can use the createBitmap() to create bitmap chunks from the original Bitmap.

    The below function takes in a bitmap and the desired chunk size (1500 in your case). And split the bitmap vertically if the width is greater than height, and horizontally otherwise.

    fun getBitmaps(bitmap: Bitmap, maxSize: Int): List<Bitmap> {
    
        val width = bitmap.width
        val height = bitmap.height
    
        val nChunks = ceil(max(width, height) / maxSize.toDouble())
    
        val bitmaps: MutableList<Bitmap> = ArrayList()
    
        var start = 0
        for (i in 1..nChunks.toInt()) {
    
            bitmaps.add(
                if (width >= height)
                    Bitmap.createBitmap(bitmap, start, 0, width / maxSize, height)
                else
                    Bitmap.createBitmap(bitmap, 0, start, width, height / maxSize)
            )
            start += maxSize
        }
    
        return bitmaps
    
    }
    

    Usage:

    getBitmaps(myBitmap, 1500)