1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
|
fun trimBitmap(bitmap: Bitmap): Bitmap { var top = 0 var bottom = bitmap.height - 1 var left = 0 var right = bitmap.width - 1 while (top < bitmap.height && isRowWhite(bitmap, top)) { top++ } while (bottom >= top && isRowWhite(bitmap, bottom)) { bottom-- } while (left < bitmap.width && isColumnWhite(bitmap, left, top, bottom)) { left++ } while (right >= left && isColumnWhite(bitmap, right, top, bottom)) { right-- } return Bitmap.createBitmap(bitmap, left, top, right - left + 1, bottom - top + 1) }
private fun isRowWhite(bitmap: Bitmap, row: Int): Boolean { for (x in 0 until bitmap.width) { if (bitmap.hasColor(x, row)) { return false } } return true }
private fun isColumnWhite(bitmap: Bitmap, column: Int, top: Int, bottom: Int): Boolean { for (y in top..bottom) { if (bitmap.hasColor(column, y)) { return false } } return true }
private fun Bitmap.hasColor(x: Int, y: Int): Boolean { val p = getPixel(x, y) return p != Color.WHITE && p != Color.TRANSPARENT }
|