Skip to content

Instantly share code, notes, and snippets.

@cashlo
Last active July 31, 2022 17:24
Show Gist options
  • Save cashlo/da518b185f577641b969af075ae7a21c to your computer and use it in GitHub Desktop.
Save cashlo/da518b185f577641b969af075ae7a21c to your computer and use it in GitHub Desktop.
Floyd-Steinberg Dithering for Kotlin Android
fun dithering(bitmap: Bitmap) {
val height: Int = bitmap.getHeight()
val width: Int = bitmap.getWidth()
val colors = 3
val threshold = 255/colors
for (x in 0 until width) {
for (y in 0 until height) {
val pixel = bitmap.getPixel(x, y)
var alpha = Color.alpha(pixel)
var originalColor = Color.blue(pixel)
var newColor = originalColor/threshold*threshold
bitmap.setPixel(x, y, Color.argb(alpha, newColor, newColor, newColor))
var quantizationError = originalColor - newColor
addColor(bitmap,x+1, y, quantizationError*7/16)
addColor(bitmap,x-1, y+1, quantizationError*3/16)
addColor(bitmap,x, y+1, quantizationError*5/16)
addColor(bitmap,x+1, y+1, quantizationError*1/16)
}
}
}
private fun addColor(bitmap: Bitmap, x: Int, y :Int, change:Int) {
if (x < 0 || y < 0){
return
}
if (x >= bitmap.width || y >= bitmap.height){
return
}
val pixel = bitmap.getPixel(x, y)
var alpha = Color.alpha(pixel)
var originalColor = Color.blue(pixel)
var newColor = originalColor+change
if (newColor > 255) {
newColor = 255
}
bitmap.setPixel(x, y, Color.argb(alpha, newColor, newColor, newColor))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment