Abhijit Shelar
Abhijit Shelar

Reputation: 1065

How to convert Color back from string?

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.

Upvotes: 1

Views: 5181

Answers (4)

Taylor Libonati
Taylor Libonati

Reputation: 21

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

Upvotes: 2

Djordje Tasic
Djordje Tasic

Reputation: 1

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);

Upvotes: 0

Daniel Rose
Daniel Rose

Reputation: 17658

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.

Upvotes: 4

Jontatas
Jontatas

Reputation: 964

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.

Upvotes: 0

Related Questions