Android bitmap trim white

源码

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
}
bitmap clip
Git commit message
Android bitmap add watermark
© 2020 qomg
Powered by hexo | Theme is blank