ps.
ps.

Reputation: 4360

Store RGB values in database

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.

Upvotes: 5

Views: 8316

Answers (6)

richardtallent
richardtallent

Reputation: 35374

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.

Upvotes: 3

Jax
Jax

Reputation: 7130

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!

Upvotes: 2

mwcz
mwcz

Reputation: 9301

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.

Upvotes: 5

Remus Rusanu
Remus Rusanu

Reputation: 294267

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.

Upvotes: 4

mauris
mauris

Reputation: 43619

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.

Upvotes: 0

Dan Cristoloveanu
Dan Cristoloveanu

Reputation: 2058

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.

Upvotes: 1

Related Questions