1

I will save Color as

colorObj.ToString()

Then it is save as Color [A=255, R=255, G=255, B=128]

Now How to convert this string back to color?

I am already solve problem by storing RGB in integer value but that value is negative and have no significance until someone apply it from code. These [A=255, R=255, G=255, B=128] ARGB values are more readable.

Abhijit Shelar
  • 1,055
  • 7
  • 21
  • 41
  • It would appear that Color.ToString() returns different values according to the version of .NET. Current docs say it should be a hex value, and I'm currently seeing a text string such has "Color [Yellow]" with .NET4. And you have something different... – winwaed Aug 18 '17 at 16:36

4 Answers4

4

You could store (and load) the color as the HTML values, for example #FFDFD991. Then use System.Drawing.ColorTranslator.ToHtml() and System.Drawing.ColorTranslator.FromHtml(). Also see this question.

Community
  • 1
  • 1
Daniel Rose
  • 17,233
  • 9
  • 65
  • 88
1

Playing off of Jontata's answer this is what I came up with.

Its a good solution for Unity users as it doesn't require the Drawing Library. I am just making my own ToString function for easy conversion.

Functions:

public static string colorToString(Color color){
    return color.r + "," + color.g + "," + color.b + "," + color.a; 
}
public static Color stringToColor(string colorString){
    try{
        string[] colors = colorString.Split (',');
        return new Color (float.Parse(colors [0]), float.Parse(colors [1]), float.Parse(colors [2]), float.Parse(colors [3]));
    }catch{
        return Color.white;
    }
}

Usage:

Color red = new Color(1,0,0,1);
string redStr = colorToString(red);
Color convertedColor = stringToColor(redStr); //convertedColor will be red
0

If you first convert Color to Int via ColorTranslator.ToWin32(Color win32Color) and then convert that Int to String, and then just convert it back to Int and that int back to Color via ColorTranslator.FromWin32(Color win32Color)

//
Color CColor = Color.FromArgb(255, 20, 200, 100);
int IColor;
String SString;
//from color to string    
IColor = ColorTranslator.ToWin32(CColor);
SString = IColor.ToString();
//from string to color    
IColor = int.Parse(SString);
CColor = ColorTranslator.FromWin32(IColor);
0

The not so elegant solution could be to split the string and extract the values you need. Something like:

var p = test.Split(new char[]{',',']'});

int A = Convert.ToInt32(p[0].Substring(p[0].IndexOf('=') + 1));
int R = Convert.ToInt32(p[1].Substring(p[1].IndexOf('=') + 1));
int G = Convert.ToInt32(p[2].Substring(p[2].IndexOf('=') + 1));
int B = Convert.ToInt32(p[3].Substring(p[3].IndexOf('=') + 1));

There must be better ways to do it though, this was the first thing to come to mind.

Jontatas
  • 954
  • 7
  • 17