Skip to content

Instantly share code, notes, and snippets.

@tsprates
Last active June 28, 2018 13:43
Show Gist options
  • Select an option

  • Save tsprates/9809288 to your computer and use it in GitHub Desktop.

Select an option

Save tsprates/9809288 to your computer and use it in GitHub Desktop.
Function to PostgreSQL to Calculate Lighter or Darker Hex Colors.
--
-- Convert to decimal and change luminosity
-- Inspired by: http://www.sitepoint.com/javascript-generate-lighter-darker-color/
--
--
-- Reverse: to_hex
-- See: http://grokbase.com/t/postgresql/pgsql-general/0541qyk9ya/help-with-converting-hexadecimal-to-decimal
CREATE OR REPLACE FUNCTION from_hex(t text) RETURNS integer AS $$
DECLARE
r RECORD;
BEGIN
FOR r IN EXECUTE 'SELECT x'''||t||'''::integer AS hex' LOOP
RETURN r.hex;
END LOOP;
END
$$ LANGUAGE plpgsql;
CREATE OR REPLACE FUNCTION ColorLuminance(cor VARCHAR, lum FLOAT) RETURNS TEXT AS $$
DECLARE
cor ALIAS FOR $1;
lum ALIAS FOR $2;
hexa TEXT;
c FLOAT;
i INTEGER := 0;
aux TEXT := '';
rgb TEXT := '#';
BEGIN
SELECT regexp_replace(cor, '[^0-9a-f]', '', 'gi') INTO hexa;
IF cor = 'transparent' THEN
RETURN 'transparent';
END IF;
IF (length(hexa) < 6) THEN
SELECT CAST( (substr(hexa, 1, 1) || substr(hexa, 1, 1) || substr(hexa, 2, 1) || substr(hexa, 2, 1) || substr(hexa, 3, 1) || substr(hexa, 3, 1)) AS VARCHAR) INTO hexa;
END IF;
FOR i IN 0..2 LOOP
SELECT from_hex(substr(hexa, (i*2+1), 2)) INTO c;
SELECT to_hex(CAST(LEAST(GREATEST(0, c+(c*lum)), 255) AS INTEGER)) INTO aux;
SELECT (rgb || substr('00' || aux, length(aux)+1)) INTO rgb;
END LOOP;
RETURN rgb;
END;
$$ LANGUAGE plpgsql;
--select ColorLuminance('#69c', 0); -- returns "#6699cc"
--select ColorLuminance('6699CC', 0.2); -- "#7ab8f5" - 20% lighter
--select ColorLuminance('#69C', -0.5); -- "#334d66" - 50% darker
--select ColorLuminance('00', 1); -- "#000000" - true black cannot be made lighter!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment