Skip to content

Instantly share code, notes, and snippets.

@peteroupc
Created November 16, 2012 09:08
Show Gist options
  • Save peteroupc/4085710 to your computer and use it in GitHub Desktop.
Save peteroupc/4085710 to your computer and use it in GitHub Desktop.
Conversion from HLS direct to HSV and back
/* This file is in the public domain. Peter O., 2012. http://upokecenter.dreamhosters.com
Public domain dedication: http://creativecommons.org/publicdomain/zero/1.0/ */
using System;
namespace PeterO
{
public class ColorUtil
{
// Assumes hsv[0] is from 0-360, and hsv[1] and hsv[2] are from 0-1
public static double[] HsvToHls(double[] hsv){
double luminance=hsv[2]*(1.0-(hsv[1]/2.0));
double saturation;
if(luminance<=0.5){
saturation=(luminance==0) ? 0 : hsv[1]*hsv[2]/(luminance*2);
} else {
double lumFactor=(0.5-(luminance-0.5));
saturation=(lumFactor==0) ? 1.0f : hsv[1]*hsv[2]/(lumFactor*2);
}
return new double[]{hsv[0],luminance,saturation};
}
// Assumes hls[0] is from 0-360, and hls[1] and hls[2] are from 0-1
public static double[] HlsToHsv(double[] hls){
double saturation=0.0;
double value=0.0;
if(hls[1]>0){
double lumScale=1.0-Math.Max(hls[1]-0.5,0)*2;
lumScale=(lumScale==0) ? 0 : 1.0/lumScale;
double lumStart=Math.Max(0,lumScale-0.5);
double lumDiv=(lumScale-lumStart);
lumDiv=(lumStart+(hls[2]*lumDiv));
saturation=(lumDiv==0) ? 0 : (hls[2]/lumDiv);
value=hls[1]+(1.0-hls[1])*hls[2];
}
return new double[]{hls[0],saturation,value};
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment