Created
April 14, 2009 09:45
-
-
Save zzkt/95090 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
;; convert a hex rgb or argb colour string to a vector of 3 or 4 floats [0..1] | |
(define (hex2rgb str) | |
(define (h2n h) | |
(/ (string->number (string-append "#x" h) 16) 255.0)) | |
(cond ((= 9 (string-length str)) | |
(let ((a (substring str 1 3)) | |
(r (substring str 3 5)) | |
(g (substring str 5 7)) | |
(b (substring str 7 9))) | |
(vector (h2n r) (h2n g) (h2n b) (h2n a)))) | |
((= 7 (string-length str)) | |
(let ((r (substring str 1 3)) | |
(g (substring str 3 5)) | |
(b (substring str 5 7))) | |
(vector (h2n r) (h2n g) (h2n b)))))) | |
;; convert a vector of 3 or 4 floats [0..1] to a hex rgb or rgba colour string | |
(define (rgb2hex rgb) | |
(define (f2h f) | |
(let ((h (number->string (inexact->exact | |
(round (* 255.0 f))) 16))) | |
(if (= 1 (string-length h)) | |
(string-append "0" h) h))) | |
(let ((r (vector-ref rgb 0)) | |
(g (vector-ref rgb 1)) | |
(b (vector-ref rgb 2)) | |
(a (if (= 4 (vector-length rgb)) | |
(vector-ref rgb 3) #f))) | |
(string-append "#" (f2h r) (f2h g) (f2h b) (if a (f2h a) "")))) | |
;; this could still be improved to check for a leading '#' and possibly | |
;; 3 character colour strings (amongst other sanity checks. ..) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment