Created
October 17, 2011 12:59
-
-
Save purcell/1292553 to your computer and use it in GitHub Desktop.
A few hacky color-related functions
This file contains 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
(defun format-color (rgb) | |
"Convert a triplet of floating point (0.0-1.0) RGB values into | |
a hex triplet" | |
(apply 'format "#%02x%02x%02x" | |
(mapcar (lambda (x) (* 255 x)) rgb))) | |
(defconst colour-triplet-regex | |
"\\([0-9A-Fa-f]\\{2\\}\\)\\([0-9A-Fa-f]\\{2\\}\\)\\([0-9A-Fa-f]\\{2\\}\\)") | |
(defun parse-colour (colour) | |
"Parse a hex colour string into a triplet of floating point (0.0-1.0) RGB values." | |
(when (string-match colour-triplet-regex colour) | |
(mapcar (lambda (x) (/ (float (string-to-int (match-string x colour) 16)) 255.0)) '(1 2 3)))) | |
(defun matrix-multiply (m1 m2) | |
(mapcar m1)) | |
;; http://en.wikipedia.org/wiki/SRGB#The_forward_transformation_.28CIE_xyY_or_CIE_XYZ_to_sRGB.29 | |
;; (matrix-multiply '((0.4124 0.3576 0.1805) | |
;; (0.2126 0.7152 0.0722) | |
;; (0.0193 0.1192 0.9505)) | |
;; srgb) | |
(defun srgb->cie-xyz (srgb) | |
(let ((r (nth 0 srgb)) | |
(g (nth 1 srgb)) | |
(b (nth 2 srgb))) | |
(list (+ (* r 0.4124) (* g 0.3576) (* b 0.1805)) | |
(+ (* r 0.2126) (* g 0.7512) (* b 0.0722)) | |
(+ (* r 0.0193) (* g 0.1192) (* b 0.9505))))) | |
(defun srgb->linear-rgb (srgb) | |
(mapcar (lambda (c) | |
(if (> c 0.04045) | |
(expt (/ (+ c 0.055) 1.055) 2.4) | |
(/ c 12.92))) | |
srgb)) | |
;; SRGB: 002b36 | |
;; 0 43 54 | |
;; Generic RGB 042028 | |
(parse-colour "ffffff") | |
(format-color (srgb->linear-rgb (parse-colour ""))) | |
(defun apply-gamma (v gamma) | |
"Apply gamma to a color value v in the range " | |
(expt v gamma)) | |
;; x = v ** gamma | |
(defun change-gamma (v old-gamma new-gamma) | |
(apply-gamma (/ 1 (log v old-gamma)) new-gamma)) | |
(defvar default-gamma 0.4545) | |
(defun adjust-gamma (hexcolor old-gamma new-gamma) | |
(let* ((rgb (parse-colour hexcolor)) | |
(new-rgb (mapcar (lambda (v) (change-gamma v old-gamma new-gamma)) rgb))) | |
(format-color new-rgb))) | |
(format-color '(0.0159 0.1265 0.1597)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment