How could I store a color in a database field?

Viewed 70905

I have to store colors in database.

How could I store a color in a best manner in the database field?, by color name or something else??

11 Answers

If its for a HTML Page, storing the #RRGGBB tag as a string is probably enough.

If its for .NET , it supports building a color from its ARGB Value

System.Drawing.Color c = System.Drawing.Color.FromArgb(int);

int x = c.ToArgb();

so you could just store that int.

Probably the colour value would be best, e.g. #FFFFFF or #FF0000

Store a colour as a 24 or 32 bit integer, like in HTML/CSS i.e. #FF00CC but converted to an integer not a string.

Integers will take up less space then strings (especially VCHARs).

Store it as an int

Use ToArgb and FromArgb to set and get the values.

I think it depends. If you just need to store the color, then hex notation should be fine. If you need to perform queries against specific color channels, then you'd want smallint fields for each color channel (be it RGB, ARGB, CYMK, etc).

So, for simple storage, keep it simple. If you need to perform analysis, you'll need to consider alternate options as dictated by your problem domain.

I suggest having a 3 column color lookup table:

ID int; Name varchar(40) null; ColorVal char(8) or int (depending on how you're representing colors)

For unnamed colors just leave the name field null

I store it as a char(9).

  • Included the '#'-sign so that I don't have to prepend it in code and use it immediately
  • Normal char instead of nchar
  • Stores the transparancy

What format are you looking to store the colors in? CMTK, RGB, Pantone? It kinda helps to know... the strictly #RGB hex format works great if its for web colors or an application but not so good if you're trying to mix paints.

Why don't you use both? Table structure would be Int ARGB for the Key and a varchar for the Name.

ARGB (Key), Name
FFFFFFFF  ,Black
FF000000  ,White
Related