Creating a screen capture with a Scala script

I recently bought the old “Kung Fu” tv series on DVD, and was frustrated that I couldn't create screen captures of it with tools like SnapNDrag. All I wanted to do was create one Kung Fu ’grasshopper’ comic strip.

So I wrote a Scala script (shell script) to create a screen capture. Here’s the source code:

exec scala -savecompiled "$0" "$@"

import java.awt._
import javax.imageio.ImageIO

if (args.length != 1) {
  println("  Usage:   script filename")
  println("  Example: screencap foo.png")

val filename = args(0)
val screenSize = Toolkit.getDefaultToolkit.getScreenSize
val rectangle = new Rectangle(0, 0, screenSize.width, screenSize.height)
val bufferedImage = (new Robot).createScreenCapture(rectangle)
ImageIO.write(bufferedImage, "png", new File(filename))

Just save that as a file named (or something similar), make it executable with chmod, and then run it like this:

$ ./ foo.png

That should create a new file named foo.png. Be careful, if foo.png already exists, this script will overwrite it. That’s on the feature list for Version 2. ;)

In summary, if you want to create a screen capture (screenshot) with Scala -- or otherwise see a Scala script -- I hope this example is helpful.