Last active
April 13, 2016 12:47
-
-
Save dainkaplan/8c8e7fd36e56079c5a75a90c8694c5b8 to your computer and use it in GitHub Desktop.
Port of https://gist.github.com/mailtruck/2411659 to Scala
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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