Writing Color Hex Values to a CSV File in VB.NET

Here we go again! Another exciting blog entry talking about programming theory. This episode comes by way of a question that appeared on the board today. Someone was looking to pick out colors from an image, convert them to a hex value and write them to a CSV file (comma separated file) for Excel. I put this in the Deep Underground Misc category because frankly I don’t know much about what this person is attempting to do, but thought it may have some nice little tidbits that others find useful. So strap in and brace yourself for another exciting episode of the Programming Underground!

Awhile back I talked about picking out colors from an image in VC++. Now I am back with a new little project that I hope answers a person’s question as well as provides something useful to someone else. This time we are going to assume you used the GetPixel() function in VB.NET to pick out a series of color objects and placed them into a 2 dimensional array.

The function below will take this array of color objects, translate them to hexidecimal color values and write them into a CSV file that Excel can load up and understand. To start we have to know a bit about the color object. This object supports many features of dealing with colors in the .NET framework. One of the methods it contains is called “ToArgb()” which means to “Alpha, Red, Green, Blue”. But you might be saying to yourself “Yeah I know what the ______ RGB is, how will we get this into hex lamer?!?!” Easy now, I have feelings and they are fragile. 🙁

Well we do that by converting it to a string and giving it “X8” as a formatting string. The “X” represents “hex” and the 8 says give me 8 digits minimum. So for instance this format string will make value = &h2045e into 0002045E in which case we pull out values 2 through 6 using substring to get 02045E.

Once we have the hex value from the particular color object, we then just have to use a nested loop to loop through the array and use a streamwriter object to write to our file. The function looks a bit like this…

Private Sub WriteToFile(ByRef colorarray(,) As Color, ByVal filename As String)
		' Create a streamwriter to write our csv
		Dim colorfile As New StreamWriter(filename)

		' Value will hold our hex color value
		Dim value As String

		' Nested loop to loop through our color array of color objects
		For i As Integer = 0 To colorarray.GetUpperBound(0)
			For j As Integer = 0 To colorarray.GetUpperBound(1)
				' Convert the color object to a hex value and pull its 6 color values
				value = colorarray(i, j).ToArgb().ToString("X8").Substring(2, 6)

				' If start of new row, just write the value
				' Otherwise append a comma to the front of it
				If j = 0 Then
					colorfile.Write(value)
				Else
					colorfile.Write(", " & value)
				End If
			Next

			' Go to next row by writing a Carriage return line feed
			colorfile.Write(ControlChars.CrLf)
		Next

		' Close the file
		colorfile.Close()

End Sub

Please read through the comments to see what I am doing at each point in the sub. The CSV format is nothing more than a series of field values separated by commas. You can consider this a “comma separated file” format. To start a new row we simply make sure there is no comma and append a carriage return line feed character to the end of the line.

This results in a CSV which has the number of columns that the graphic has and the number of rows the graphic has. So for instance if the image we load up was 100 x 50 then our CSV file will have 100 columns and 50 rows. If the image was having a black border then you should see 000000 in row 1, column 1 and column 100 and lastly row 50.

You may see your CSV look like this…

40204	 40204	  40204	  40204	  40204
40204	 FCFEFC	 FCFEFC	 FCFEFC	 FCFEFC
40204	 FCFAFC	 FCFEFC	 FCFAFC	 FCFEFC
40204	 FCFEFC	 FCFEFC	 FCFEFC	 FCFEFC
40204	 FCFAFC	 FCFEFC	 FCFAFC	 FCFEFC
40204	 FCFEFC	 FCFEFC	 FCFEFC	 FCFEFC
40204	 FCFAFC	 FCFEFC	 FCFAFC	 FCFEFC
40204	 FCFEFC	 FCFEFC	 FCFEFC	 FCFAFC
40204	 FCFAFC	 FCFEFC	 FCFEFC	 FCFEFC
40204	 FCFEFC	 FCFEFC	 FCFEFC	 B4B2B4
40204	 FCFAFC	 F4F6F4	 FCFEFC	 545654

Note that the values above are only the top left corner of our image but as you can see it has a border of the color 040204 (leading zeros are stripped).

So I guess you could say that this function gives you a hex value color layout of an image. But there are going to be some limitations… at least in Excel 2003. Excel has column and row limitations. These limitations are 255 for columns and 65535 for rows. So your pictures should be checked for their dimensions first before running this function to make sure they are not bigger than what Excel can handle.

This process can also form the basis for creating functions which will build new types of pictures, maybe alter colors (by altering values and then writing the colors back into a picture) or perhaps even creating some ASCII art… but that is just a theory for now and I have yet to actually try it. Perhaps you can take it to the next level.

So that covers this little exercise and hopefully this little bit of code helps you build a great project. Feel free to take this code free of charge like everything on the Programming Underground. This is in the public domain and perfect for grabbing and altering for your twisted purposes.

Thanks again for reading! 🙂

About The Author

Martyr2 is the founder of the Coders Lexicon and author of the new ebooks "The Programmers Idea Book" and "Diagnosing the Problem" . He has been a programmer for over 25 years. He works for a hot application development company in Vancouver Canada which service some of the biggest tech companies in the world. He has won numerous awards for his mentoring in software development and contributes regularly to several communities around the web. He is an expert in numerous languages including .NET, PHP, C/C++, Java and more.