I am trying to write a C# program designed to convert a .bmp file into binary.
The file is 16×16 pixels. Each black pixel represents a one in binary, so the number 10 would be █[]█[][][][][]
The problem I am having is that my code is not recognizing the black pixels, so the output is always zero.
public Bitmap imgToDecode;
private void button2_Click(object sender, EventArgs e)
{
int i = (imgToDecode.Height * imgToDecode.Width);
bool[] pixData = new bool[i];
int p = 0;
for (int k = 1; k < imgToDecode.Height; k++)
{
for (int m = 1; m < imgToDecode.Width; m++)
{
if (imgToDecode.GetPixel(m, k) == Color.Black)
{
pixData[p] = true;
}
else
{
pixData[p] = false;
}
p++;
}
}
for (int n = 0; n < pixData.Length; n++)
{
textBox2.Text = (textBox2.Text + (Convert.ToInt32(pixData[n])));
}
}
If anyone has an idea as to why the output is 0, could they please help me. Also any ways of improving the code would be welcomed.
The source of the problem is probably that Color.Black is not equal to Color.FromArgb(0, 0, 0).
The solution would probably be to change the line:
to:
or even better, declare a variable containing the (0,0,0) color and then use it in this if statement.
So do something like:
in the beginning of your method and then change if to:
UPDATE:
There seemed to be some minor issues with loops start values. I’ve updated your code.
If you don’t need pixData array to contain bool values, you can change it to int and asign 1 or 0. This way you don’t have to convert it later :).