0

I have some code lines. I just want to convert a gray-scale image to a binary image. It look so simple but i don't understand where is wrong! Can you tell me where is it wrong. Here is it:

private void convert()
        {
            try
            {
                OpenFileDialog op = new OpenFileDialog();
                op.InitialDirectory = "D:/";
                op.Filter = "All Files|*.*|JPEGs|*.jpg|Bitmaps|*.bmp|GIFs|*.gif";
                op.FilterIndex = 1;

                if (op.ShowDialog() == DialogResult.OK)
                {
                    pictureBox3.Image = Image.FromFile(op.FileName);
                    pictureBox3.SizeMode = PictureBoxSizeMode.StretchImage;
                    pictureBox3.BorderStyle = BorderStyle.Fixed3D;

                    Bitmap img = new Bitmap(op.FileName);
                    int width = img.Width;
                    int height = img.Height;
                    string t = "";
                    for (int i = 0; i < width; i++)
                    {
                        for (int j = 0; j < height; j++)
                        {
                            if (img.GetPixel(j, i).A > 100 && img.GetPixel(j, i).B > 100 && img.GetPixel(j, i).G > 100 && img.GetPixel(j, i).R > 100)

                            {
                                t = t + "0";
                            }
                            else
                            {
                                t = t + "1";
                            }
                        }
                        t = t + "\r\n";
                    }
                    textBox1.Text = t;
                }
            }
            catch { };
        }

Thanks all!

1 Answers1

0
  • you mistake i and j in GetPixel(width, height)
  • may be img.GetPixel(j, i).A > 100 is redundant
  • catch { }; this is your main problem. you are hiding an exception and amazing
  • use StringBuilder

so:

private void Convert()
{        
    OpenFileDialog op = new OpenFileDialog();
    op.InitialDirectory = "D:/";
    op.Filter = "All Files|*.*|JPEGs|*.jpg|Bitmaps|*.bmp|GIFs|*.gif";
    op.FilterIndex = 1;

    if (op.ShowDialog() == DialogResult.OK)
    {
        pictureBox3.Image = Image.FromFile(op.FileName);
        pictureBox3.SizeMode = PictureBoxSizeMode.StretchImage;
        pictureBox3.BorderStyle = BorderStyle.Fixed3D;
        Bitmap img = new Bitmap(op.FileName);
        StringBuilder t = new StringBuilder();
        for (int i = 0; i < img.Width; i++)
        {
            for (int j = 0; j < img.Height; j++)
            {
                    t.Append((img.GetPixel(i, j).R > 100 && img.GetPixel(i, j).G > 100 &&
                             img.GetPixel(i, j).B > 100) ? 0 : 1);
            }
            t.AppendLine();
        }
        textBox1.Text = t.ToString();
    }
}
burning_LEGION
  • 13,246
  • 8
  • 40
  • 52