DitherKt

A quick rewrite of my old command-line dithering project in Kotlin. Available on Github

class Filter2By2Bayer : Filter() {
    override fun process(source: BufferedImage): BufferedImage {

        val width = source.width
        val height = source.height

        val filtered = BufferedImage(width, height, BufferedImage.TYPE_INT_RGB)

        val matrix = arrayOf(
            intArrayOf(1, 3),
            intArrayOf(4, 2)
        )

        for (y in 0 until height) {
            for (x in 0 until width) {

                var gray = source.getRGB(x, y) shr 16 and 0xFF

                gray += gray * matrix[x % 2][y % 2] / 5

                when {
                    gray < threshold -> filtered.setRGB(x, y, BLACK)
                    else -> filtered.setRGB(x, y, WHITE)
                }
            }
        }

        return filtered
    }
}
2x2 Ordered dithering example code above, if you’ve seen similar written in Java you’ll appreciate how much more beautiful Kotlin is.

2x2 Ordered dithering example code above, if you’ve seen similar written in Java you’ll appreciate how much more beautiful Kotlin is.