将图像表示为1和0数字(矩阵)

时间:2015-10-07 10:31:05

标签: c# winforms

我有问题。我想将图像表示为矩阵中的1和0数字。这是我的代码:

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";
    }
}

点击按钮3后,文本框没有显示任何内容。有人可以解释该代码有什么问题吗?

编辑:它有效。谢谢MajkeloDev

1 个答案:

答案 0 :(得分:2)

因为您将textBox1.Text设置为\ n:

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

对于这样的任务,我建议使用一个字符串构建器,这样你就不会在每次迭代完成后只更新一次UI,请参阅重构代码:

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