[Fluxus] rgb & hex colour conversion
nik gaffney
nik at fo.am
Thu Apr 9 04:00:22 PDT 2009
On 09/04/2009 11:33, gabor papp wrote:
>> here are a pair of functions to convert between rgb and hex colour
>> descriptions, eg. "#ffffff" -> (255 255 255). im not sure where they
>
> thanks nik. i needed functions like these in the past. i think these
> could be part of fluxus, but it would be easier to use them if they
> converted from/to fluxus colour values, e.g. #(1.0 1.0 1.0) instead of
> (255 255 255), and use vectors instead of lists.
sure. i just wanted to get something working, then we deal with feature
creep ;)
i couldn't quite remember if fluxus used lists or vectors for colours,
so here is a version for vectors (and possibly alpha). ..
;; convert a hex rgb or argb colour string to a list 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 list 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. ..)
> also we should take
> care of the alpha value also, so the function could take 3 or 4 element
> vectors and #aarrggbb or #rrggbb format strings. or should we use
depending on whether #aarrggbb should be converted to #(a r g b) or #(r
g b a) the above might need to change a bit.
> hexadecimal numbers instead of strings? #xffffff instead of "#ffffff".
i would suggest going with the more widespread 'html' convention as
default, rather than the PLT compatible representation.
More information about the Fluxus
mailing list