Skip to content

Instantly share code, notes, and snippets.

@awwsmm
Created October 26, 2017 20:37
Show Gist options
  • Save awwsmm/7649d0356cfc88871e0a07aaf3eeba90 to your computer and use it in GitHub Desktop.
Save awwsmm/7649d0356cfc88871e0a07aaf3eeba90 to your computer and use it in GitHub Desktop.
Methods for converting RGB <-> HSV <-> Hex <-> decimal in Scala / Java
// converts Int -> 6-digit hex String
def dec2hex(dec: Int): String = String.format("%6s", dec.toHexString.toUpperCase).replace(' ','0')
// converts any hex String to Int
def hex2dec(hex: String): Int = Integer.parseInt(hex, 16)
// convert Hue, Saturation, Value -> Red, Green, Blue
// ([Any]%360, [0,1], [0,1]) -> ([0,255], [0,255], [0,255])
def hsv2rgb(hsv: List[Double]): List[Double] = {
val colorCode = Color.HSBtoRGB(hsv(0).toFloat, hsv(1).toFloat, hsv(2).toFloat)
var rgbaBuffer: ListBuffer[Double] = List.fill(3)(0.0).to[ListBuffer]
rgbaBuffer(0) = ((colorCode & 0x00ff0000) >> 16).toDouble // r
rgbaBuffer(1) = ((colorCode & 0x0000ff00) >> 8).toDouble // g
rgbaBuffer(2) = ((colorCode & 0x000000ff) ).toDouble // b
// rgbaBuffer(3) = (((colorCode & 0xff000000) >> 24) & 0x000000ff).toDouble/255.0 // alpha
rgbaBuffer.toList
}
// convert Red, Green, Blue -> Hue, Saturation, Value
// ([0,255], [0,255], [0,255]) -> ([0,1], [0,1], [0,1])
def rgb2hsv(rgb: List[Double]): List[Double] = {
Color.RGBtoHSB(rgb(0).toInt, rgb(1).toInt, rgb(2).toInt, null).to[List].map(_.toDouble)
}
// converts hex String to Hue, Saturation, Value ([Any]%360, [0,1], [0,1])
def hex2hsv(hex: String) =
rgb2hsv(List(hex2dec(hex.substring(0,2)).toDouble,
hex2dec(hex.substring(2,4)).toDouble,
hex2dec(hex.substring(4,6)).toDouble))
// converts Hue, Saturation, Value ([Any]%360, [0,1], [0,1]) to hex String
def hsv2hex(hsv: List[Double]): String = {
val rgb = hsv2rgb(hsv)
val rhex = String.format("%2s", rgb(0).toInt.toHexString.toUpperCase).replace(' ','0')
val ghex = String.format("%2s", rgb(1).toInt.toHexString.toUpperCase).replace(' ','0')
val bhex = String.format("%2s", rgb(2).toInt.toHexString.toUpperCase).replace(' ','0')
rhex + ghex + bhex
}
def rgb2hex(rgb: List[Double]) = hsv2hex(rgb2hsv(rgb))
def hex2rgb(hex: String) = hsv2rgb(hex2hsv(hex))
def rgb2dec(rgb: List[Double]) = hex2dec(rgb2hex(rgb))
def hsv2dec(hsv: List[Double]) = hex2dec(hsv2hex(hsv))
def dec2rgb(dec: Int) = hex2rgb(dec2hex(dec))
def dec2hsv(dec: Int) = hex2hsv(dec2hex(dec))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment