fun trimBitmap(bitmap: Bitmap): Bitmap {
var bottom = bitmap.height - 1
var right = bitmap.width - 1
while (top < bitmap.height && isRowWhite(bitmap, top)) {
while (bottom >= top && isRowWhite(bitmap, bottom)) {
while (left < bitmap.width && isColumnWhite(bitmap, left, top, bottom)) {
while (right >= left && isColumnWhite(bitmap, right, top, bottom)) {
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)) {
private fun isColumnWhite(bitmap: Bitmap, column: Int, top: Int, bottom: Int): Boolean {
if (bitmap.hasColor(column, y)) {
private fun Bitmap.hasColor(x: Int, y: Int): Boolean {
return p != Color.WHITE && p != Color.TRANSPARENT