Skip to content

Instantly share code, notes, and snippets.

@zzkt
Created April 14, 2009 09:45
Show Gist options
  • Save zzkt/95090 to your computer and use it in GitHub Desktop.
Save zzkt/95090 to your computer and use it in GitHub Desktop.
;; 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