If I am using .Net and SQL Server 2008, what is the best way for me to store a color in the database, should I use ToString or convert it to an integer, or something else?
Edit:
All I want from the colour is to be able to retrieve it and draw something on the screen in the specified colour. I don't need to be able to query against it.
Well, I'd store them as six digit hex codes. That opens up the interesting possibility of actually searching for colors between other colors. If you really want to make it powerful, keep the R, G, B hex numbers in three columns. That lets you find colors which contain so much red, or ones that are similar to another color (sort by average difference of the three values).
How to store information in a database depends on how you intend to use and access it. There's no saying what the best way to store it is without knowing how you'll use it.
If you are storing the
System.Drawing.Color
, you need to store 4 bytes that represent the alpha and the 3 color channels. You can use aint
data type.If you are storing the
System.Windows.Media.Color
(from WPF), there are two possibilities depending on the usage you are using:int
data type.Depends so much on the type of color you want to store. Eg. if it is from a fixed palette then a short int or even an unsigned byte might be sufficient.
3 byte RGB or 4 byte ARGB (A=alpha, ie. transparency) could fit into 32 bit, so a 32 bit unsigned integer type would work. This is the standard for most applications. However, you might want more - in which case a 64 bit unsigned integer might be required.
Alternatively, if you want to modify or query the color according to its components, I would store each component as its own unsigned int (ie. Red, Green, Blue, Alpha fields).
How are the colors stored natively?
If you're just using 0xRRGGBB format, you may as well store it as an integer in the database, and re-hexify it when you
SELECT
(for readability).Color can be surprisingly tricky on some industries like digital cameras, desktop publishing, sanners and other. Most programmers associate color with the 24 bit color (RGB usually), some associate it with the 32 bit (RGBA). The few that work in industries like DTP that make heavy use of color have a richer set of terms that includes color correction, color space and so on and so forth. So what exactly do you need to store?