views:

192

answers:

2

Heyo, I'm messing with converting images to ASCII ones. For this I load the image, use getPixel() on each pixel, then insert a character with that colour into a 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 does return the correct colour, but the text only end up black. If I change

this

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

to this

richTextBox1.SelectionColor = Color.Red;

It works fine.

Why am I not getting the right colours?

(I know it doesn't do the new lines properly, but I thought I'd get to the bottom of this issue first.)

Thanks

+1  A: 

Well, this section looks suspicious to me:

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

            richTextBox1.Text += "\n";
        }

       x++; 

So if x is >- width-1, you set x to 0 and then increment it to 1 out side the conditional. Would think it wouldn't increment if you set it to 0.


Edit: And upon thinking about this some more, why not iterate on the width & height in nested loops and simplify things a bit. Something like:

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

because you are driving this thing off of the size of the image, right? The position in the RTB is dependent upon where you are in the Bitmap.

itsmatt
+1  A: 

Your issue is being caused by using += to set the Text value. Using += is causing your formatting to be lost by re-setting the Text value and assigning a new string value.

You need to change your code to use Append() instead.

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

From MSDN:

You can use this method to add text to the existing text in the control instead of using the concatenation operator (+) to concatenate text to the Text property.

Chris Persichetti