views:

220

answers:

6

I never had to do this before and never even thought about this before. How can i or what is the best way of storing RGB values in the database.

I thought of couple of options. The most obvious one being 3 byte columns to store the R,G and the B.(I dont want to go this route) Another option is to store it in a 32 bit int column. ( I am leaning towards this one)

or may be i am just missing something trivial.

+1  A: 

Just store it as a 32 bit value. There is no point in breaking down into 3 fields since you will most likely want all 3 components together all the time.

Dan Cristoloveanu
A: 

My guess is to store a 32 bit integer.

However if your SQL operations require each component to be of individual columns (meaning to say you need to compare values of R vs G of another column for example) you will have to separate out the values into individual columns. R, G, B, each 0-255 integer.

thephpdeveloper
+2  A: 

RGB values are usually described on the web in the format 0xRRGGBB where RR, GG, and BB are the hex values of R, G, and B. While you may be wasting a bit of space with a 32 bit int, I can't imagine it's much compared to the benefit you'll potentially gain from storing the values in a well-known format.

In case you'd like quick primer on how to go about the conversion, wikipedia's got you covered!

Jax
+3  A: 

First and foremost: what are your requirements?

Do you need to retrieve the color and only the color? Do you ever need to query be components? do you need to search by colorspace distance? Do you need to store colorspace information (Adobe RGB or sRGB)? See also Best Way to represent a color in SQL.

Remus Rusanu
I just needed to retrieve the color. Thanks for link and the reply
ps
+3  A: 

The "wasted" space of 32-bit integer column would allow you to store an alpha channel as well, should the need ever arise for it.

mwc
A: 

If you're doing storing these numbers for web design, I would suggest simply using a char(6) and storing a string of hex triplets.

Sure, that's two bytes "wasted" over a 32-bit integer, but if you're not comparing them mathematically in some way and just regurgitating them to a CSS file, for instance, storing as a string will remove the need to translate back and forth.

Not that hex triplets to integers is a tough translation, but doing the easiest thing possible rather than optimizing for a few bytes may be worth considering.

If you're doing something other than web-related work, you may want to consider building in room for more than 8 bits per channel.

richardtallent