Skip to content

Instantly share code, notes, and snippets.

@dainkaplan
Last active April 13, 2016 12:47
Show Gist options
  • Save dainkaplan/8c8e7fd36e56079c5a75a90c8694c5b8 to your computer and use it in GitHub Desktop.
Save dainkaplan/8c8e7fd36e56079c5a75a90c8694c5b8 to your computer and use it in GitHub Desktop.
object ColorMeter {
def hexToRGB(hex: String): (Int,Int,Int) = {
def toInt(str: String)(s: Int, e: Int) =
Integer.parseInt(str.substring(s,e), 16)
val hex_1 = if (hex(0)=='#') hex.substring(1,7) else hex
val r = toInt(hex_1)(0,2)
val g = toInt(hex_1)(2,4)
val b = toInt(hex_1)(4,6)
(r, g, b)
}
def percents(rgb:(Int,Int,Int)):(Double,Double,Double) = {
val p1 = (rgb._1 / 255d) * 100
val p2 = (rgb._2 / 255d) * 100
val p3 = (rgb._3 / 255d) * 100
(p1,p2,p3)
}
def average(rgb:(Double,Double,Double)): Double = {
math.round((rgb._1 + rgb._2 + rgb._3) / 3)
}
// 0 = same color; 100 = completely different, e.g. "000000" and "ffffff"
def percentDifferent(cwith: String, ccolor: String): Double = {
if (cwith.isEmpty && ccolor.isEmpty) 0d // Entirely same
if (cwith.isEmpty || ccolor.isEmpty) 100d // Entirely different
else {
val rgb1 = percents(hexToRGB(cwith))
val rgb2 = percents(hexToRGB(ccolor))
math.abs(average(rgb1) - average(rgb2))
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment