Skip to content

Instantly share code, notes, and snippets.

@betaveros
Created December 16, 2014 13:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save betaveros/8a2d1b48ee04f07a245b to your computer and use it in GitHub Desktop.
Save betaveros/8a2d1b48ee04f07a245b to your computer and use it in GitHub Desktop.
import java.awt.image.BufferedImage
import java.io.File
import java.awt.Color
import javax.imageio.ImageIO
object ImageTabler {
var classMap: Map[Int, Int] = Map()
var nextClass: Int = 1
def addClassFor(c: Int): Unit = if (!(classMap contains c)) {
var cls = nextClass
classMap += (c -> cls)
nextClass += 1
}
def groupEqual[T](xs: Traversable[T]): List[(Int, T)] = xs.headOption match {
case Some(t) => { val (ts, rest) = xs.span(t == _); (ts.size, t) :: groupEqual(rest) }
case None => Nil
}
def main(args: Array[String]): Unit = {
Option(ImageIO.read(new File(args(0)))) match {
case Some(img) => {
for (y <- 0 until img.getHeight(); x <- 0 until img.getWidth()) { addClassFor(img.getRGB(x, y)) }
println("""<html><head><style>
.w { width: 20px; height: 0; }
.h { width: 0; height: 20px; }
table, tr, td { border-width: 0; padding: 0; margin: 0; border-collapse: collapse; }
td:hover { box-shadow: 0 0 10px black; }
""")
for ((color, cls) <- classMap.toSeq.sortBy(_._2)) {
println(".c%d { background-color: #%06X; }".format(cls, color & 0xffffff))
}
println("""</style></head>
<body><table>
<tr><td></td>""")
0 to img.getHeight() foreach { _ => print("<td class='w'></td>") }
print("</tr>")
var a = Array.fill(img.getHeight, img.getWidth)(0)
for (y <- 0 until img.getHeight) {
var x = 0
while (x < img.getWidth) {
val x0 = x
while (x < img.getWidth && img.getRGB(x0, y) == img.getRGB(x, y)) x += 1
a(y)(x0) = x - x0
}
}
for (y <- 0 until img.getHeight) {
print("<tr><td class='h'></td>")
for (x <- 0 until img.getWidth) {
val xlen = a(y)(x)
if (xlen != 0) {
var ye = y
while (ye < img.getHeight && img.getRGB(x, y) == img.getRGB(x, ye) && xlen == a(ye)(x)) ye += 1
for (y1 <- y until ye; x1 <- x until (x + xlen)) a(y1)(x1) = 0
print("<td rowspan='%d' colspan='%d' class='c%s'></td>".format(ye - y, xlen, classMap(img.getRGB(x, y))))
}
}
println("</tr>")
}
println("</table></body></html>")
}
case None => println("Cannot read :(")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment