teaching machines

CS 330 Lecture 33 – OOP and HOF via Scala

April 27, 2015 by . Filed under cs330, lectures, spring 2015.

Agenda

Intentions

TODO

Code

Image.scala

import java.util.Scanner
import java.awt.image.BufferedImage
import java.awt.Color
import java.io.File
import scala.math.min

class Image(val path: String) {
  private val in : Scanner = new Scanner(new File(path))

  in.nextLine // skip P3
  val width = in.nextInt
  val height = in.nextInt
  in.nextInt

  val colors = new Array[Color](width * height)
  for (i <- 0 until (width * height)) {
    colors(i) = new Color(in.nextInt, in.nextInt, in.nextInt)
  }

  in.close

  def apply(c: Int, r: Int): Color = {
    colors(c + r * width)
  }

  def toSepia: BufferedImage = {
    val image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB)

    for (c <- 0 until width; r <- 0 until height) {
      val rgb = this(c, r)
      val red   = min(255, (rgb.getRed * 0.393 + rgb.getGreen * 0.769 + rgb.getBlue * 0.189).toInt)
      val green = min(255, (rgb.getRed * 0.349 + rgb.getGreen * 0.686 + rgb.getBlue * 0.168).toInt)
      val blue  = min(255, (rgb.getRed * 0.272 + rgb.getGreen * 0.534 + rgb.getBlue * 0.131).toInt)
      image.setRGB(c, r, new Color(red, green, blue).getRGB)
    }

    image
  }
}

Main.scala

import java.io.File
import javax.imageio.ImageIO

object Main {
  def main(args: Array[String]) {
    val image = new Image(args(0))
    println(image.width)
    println(image.height)
    ImageIO.write(image.toSepia, "png", new File(args(1)))
  }
}

Haiku

Art’s not truth, but lies
Lies that make us realize truth
— Pablo Picasso