skip to content
Posts · February 2024

Android bitmap trim white


源码

/**
* 去除多余白框
*/
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
}