1

嘿嘿,我正在把图像转换为 ASCII 图像。为此,我加载图像,在每个像素上使用 getPixel(),然后将具有该颜色的字符插入到 RichTextBox 中。

        Bitmap bmBild = new Bitmap(openFileDialog1.FileName.ToString()); // valid image

        int x = 0, y = 0;

        for (int i = 0; i <= (bmBild.Width * bmBild.Height - bmBild.Height); i++)
        {
            // Ändra text här
            richTextBox1.Text += "x";
            richTextBox1.Select(i, 1);

            if (bmBild.GetPixel(x, y).IsKnownColor)
            {

                richTextBox1.SelectionColor = bmBild.GetPixel(x, y);
            }
            else
            {
                richTextBox1.SelectionColor = Color.Red;
            }


            if (x >= (bmBild.Width -1))
            {
                x = 0;
                y++;

                richTextBox1.Text += "\n";
            }

           x++; 
        }

GetPixel 确实返回正确的颜色,但文本仅以黑色结束。如果我改变

richTextBox1.SelectionColor = bmBild.GetPixel(x, y);

对此

richTextBox1.SelectionColor = Color.Red;

它工作正常。

为什么我没有得到正确的颜色?

(我知道它没有正确地做新的线路,但我想我会先搞清楚这个问题的根源。)

谢谢

4

2 回答 2

1

好吧,这部分对我来说看起来很可疑:

        if (x >= (bmBild.Width -1))
        {
            x = 0;
            y++;

            richTextBox1.Text += "\n";
        }

       x++; 

因此,如果 x >-width-1,则将 x 设置为 0,然后在条件之外将其增加到 1。如果您将其设置为 0,它会认为它不会增加。


编辑: 再考虑一下,为什么不在嵌套循环中迭代宽度和高度并简化一些事情。就像是:

int col = 0;
int row = 0;
while (col < bmBild.Height)
{
   row = 0;
   while (row < bmBild.Width)
   {
       // do your stuff in here and keep track of the position in the RTB
       ++row;
   }
   ++col;
}

因为你把这个东西从图像的大小上赶走了,对吧?RTB 中的位置取决于您在位图中的位置。

于 2010-04-16T17:49:33.510 回答
1

您的问题是由使用 += 设置 Text 值引起的。使用 += 会通过重新设置 Text 值并分配新的字符串值而导致格式丢失。

您需要更改代码以改用 Append()。

 richTextBox1.Append("x");
richTextBox1.Append("\n");

来自 MSDN:

您可以使用此方法将文本添加到控件中的现有文本,而不是使用连接运算符 (+) 将文本连接到 Text 属性。

于 2010-04-19T18:04:53.293 回答