0

I have a problem. I want to represent an image into 1 and 0 number in matrix. This is my code:

private void button3_Click(object sender, EventArgs e)
{
    Color originalColor;
    int grayScale;

    File2 = new Bitmap(File);
    for (int i = 0; i < File2.Height; i++)
    {
        for (int j = 0; j < File2.Width; j++)
        {
            textBox1.Text = "a";
            originalColor = File2.GetPixel(i, j);
            grayScale = (int)((originalColor.R) + (originalColor.G) + (originalColor.B)) / 3;
            if (grayScale > 127)
            {
                textBox1.Text += "1 ";
            }
            else
            {
                textBox1.Text += "0 ";
            }
        }
        textBox1.Text += "\n";
    }
}

The textbox doesn't show anything after I click the button3. Can someone explain what's wrong with that code?

EDIT: it works. thanks MajkeloDev

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
  • 2
    textBox1.Text = "\n"; **replaces** existing text. Also I wouldn't perform such big operation directly using TextBox, construct your text using StringBuilder and assign textBox1.Text once. Last note: your algorithm to transform to gray scale is not accurate (see also http://stackoverflow.com/q/9839013/1207195) and even worse is the thresholding to convert to B/W... – Adriano Repetti Oct 07 '15 at 10:34
  • Did You find a solution ? – MajkeloDev Oct 07 '15 at 10:51

1 Answers1

2

Because you are setting textBox1.Text to \n:

textBox1.Text = "\n"; // You propably wanted to use += operator

For tasks like this I would suggest to use a string builder so You won't be updating UI every iteration just once after it's finished, see refactored code:

private void button3_Click(object sender, EventArgs e)
{
    Color originalColor;
    int grayScale;
    var sb = new StringBuilder();
    File2 = new Bitmap(File);
    for (int i = 0; i < File2.Height; i++)
    {
        for (int j = 0; j < File2.Width; j++)
        {
            sb.Append("a");
            originalColor = File2.GetPixel(i, j);
            grayScale = (int)((originalColor.R) + (originalColor.G) + (originalColor.B)) / 3;
            if (grayScale > 127)
            {
                sb.Append("1 ");
            }
            else
            {
                sb.Append("0 ");
            }
        }
        sb.Append("\n");
    }
    // after all iterations
    textBox1.Text = sb.ToString();
}
MajkeloDev
  • 1,661
  • 13
  • 30