Writing Processing in Kotlin

Hi hi. Recently I posted the same program written in Processing/Java and OPENRNDR/Kotlin:

which loads all images in a folder, gets a slice of each image, sorts the slices by saturation and brightness, and draws them stacked.

Here is now the same program in Processing/Kotlin. See how short it is.

It shows that, unlike Kotlin programs above in this page, there’s no need for a companion object at all to launch the PApplet but just one line invoking PApplet.main().

import processing.core.PApplet
import java.io.File

fun main() = PApplet.main(CCSPoster88::class.java.name)

class CCSPoster88 : PApplet() {
    override fun settings() = size(1200, 675)

    override fun setup() {
        background(0)
        val files =
            File("/home/funpro/www/Stammtisch/assets/img/large").listFiles()
        val d = height / files.size.toFloat()
        val slices = files.map {
            val img = loadImage(it.absolutePath)
            img[0, img.height / 2, img.width, d.toInt()]
        }.sortedBy { slice ->
            slice.pixels.sumOf {
                max(saturation(it), 255 - brightness(it)).toDouble()
            } / slice.pixels.size
        }
        stroke(0, 20f)
        slices.forEachIndexed { i, slice ->
            image(slice, 0f, i * d, width.toFloat(), d)
            line(0f, i * d, width.toFloat(), i * d)
        }
    }

    override fun draw() {}
}

One thing that may be surprising / confusing is that since PImage has a get method, it can be accessed just with square brackets in Kotlin. That was not really intentional: when the PImage.get was created Kotlin didn’t exist. Since Kotlin removes the get() part from any getBlaBla() java method, there is no method name left in this case :slight_smile: Instead of img.get(x, y, w, h) it’s just img[x, y, w, h] to get a crop of the PImage.

Happy 20 year Processing anniversary! :fireworks: :cake:

5 Likes