Search code examples
c#colorssystem.drawing

Casting a RGB string to a Color type


I am reading from a file that has a list of RGB values, i.e.

0,1,6
0,2,6
0,43,170
0,42,168
0,44,175
0,44,176
0,44,176
0,221,255
0,222,255
0,222,255

I have stored all these values into a string[] array, with this constructor:

    public Program(int rows, String fileLocation) {

        int i;
        String line;
        count = 0;
        this.rows = rows;
        this.fileLocation = fileLocation;
        stringArray = new String[rows];

        try {
            System.IO.StreamReader file = new System.IO.StreamReader(fileLocation);
            for (i = 0; i < rows; i++) {
                while ((line = file.ReadLine()) != null) {
                    stringArray[i] = line;
                    count++;
                    break;
                }
            }
        }
        catch (Exception e) {
            throw (e);
        }
    }

I wanted to convert these current Strings to Color values, as they are just RGB values in the form of Strings.

So I used this method:

    public Color[] convertToColorArray() {
        for (int i = 0; i < rows; i++) {
            colorArray[i] = System.Drawing.Color.FromArgb(stringArray[i]);
        }
        return colorArray;
    }

With that said, I am getting the following error:

enter image description here

Telling me I have an invalid arg. I understand that the argument is not necessarily something like this 255,255,255 which are three ints separated by commas, but my string input is in that format. What is it I should do? Should I cast it to something? Should I simply store those values into a Color[] in my constructor in the beginning?


Solution

  • look at the overloads for Color.FromArgb, they all expect int to be passed in. So no, you can't just pass in a string and expect it to work. However it is not hard to turn your string in to a set of ints.

    public Color[] convertToColorArray() {
        for (int i = 0; i < rows; i++) {
            //This gives us an array of 3 strings each representing a number in text form.
            var splitString = stringArray[i].Split(','); 
    
            //converts the array of 3 strings in to an array of 3 ints.
            var splitInts = splitString.Select(item => int.Parse(item)).ToArray(); 
    
            //takes each element of the array of 3 and passes it in to the correct slot
            colorArray[i] = System.Drawing.Color.FromArgb(splitInts[0], splitInts[1], splitInts[2]); 
        }
        return colorArray;
    }
    

    This code all assumes your source file is well formed so that string.Split will always return at least 3 arrays and int.Parse will never fail at parsing the input.