[OT] Round 2: Webpage design and "Name That Color!"

Adam D. Ruppe destructionator at gmail.com
Sun Feb 27 17:41:11 PST 2011


Here's a small program to convert HSL to RGB. Usage "hsl 60 1 0.5" for example,
where 60 is hue, 1 is saturation and 0.5 is lightness.

import std.stdio;
import std.math;
import std.conv;

struct Color {
	ubyte r;
	ubyte g;
	ubyte b;
	ubyte a;
}

Color fromHsl(real h, real s, real l) {
	h = h % 360;

	real C = (1 - abs(2 * l - 1)) * s;

	real hPrime = h / 60;

	real X = C * (1 - abs(hPrime % 2 - 1));

	real r, g, b;

	if(h is real.nan)
		r = g = b = 0;
	else if (hPrime >= 0 && hPrime < 1) {
		r = C;
		g = X;
		b = 0;
	} else if (hPrime >= 1 && hPrime < 2) {
		r = X;
		g = C;
		b = 0;
	} else if (hPrime >= 2 && hPrime < 3) {
		r = 0;
		g = C;
		b = X;
	} else if (hPrime >= 3 && hPrime < 4) {
		r = 0;
		g = X;
		b = C;
	} else if (hPrime >= 4 && hPrime < 5) {
		r = X;
		g = 0;
		b = C;
	} else if (hPrime >= 5 && hPrime < 6) {
		r = C;
		g = 0;
		b = X;
	}

	real m = l - C / 2;

	r += m;
	g += m;
	b += m;

	return Color(
		cast(ubyte)(r * 255),
		cast(ubyte)(g * 255),
		cast(ubyte)(b * 255),
		255);
}

void main(string[] args) {
	auto color = fromHsl(to!real(args[1]), to!real(args[2]), to!real(args[3]));

	writefln("#%02x%02x%02x", color.r, color.g, color.b);
}


More information about the Digitalmars-d mailing list