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:

#!/bin/sh
exec scala -savecompiled "$0" "$@"
!#

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

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

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 screencap.sh (or something similar), make it executable with chmod, and then run it like this:

$ ./screencap.sh 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.