Convert a Color Image into Grayscale

Amroomi
Posted by Amroomi under C# category on | Points: 40 | Views : 2074
First create a new C# Windows Form Application, Add two picture boxes and a button. (I am using default names of the controls.)

Set an image for the first Picture Box (pictureBox1)

Add the following code to the button click event.

Bitmap bitmap1 = new Bitmap(pictureBox1.Image);

int width1 = bitmap1.Width;
int height1 = bitmap1.Height;

Bitmap bitmap2 = new Bitmap(width1, height1);

for (int i = 0; i < width1; i++)
{
for (int j = 0; j < height1; j++)
{
Color color1 = bitmap1.GetPixel(i, j);

byte R = color1.R;
byte G = color1.G;
byte B = color1.B;

int common = (R + G + B) / 3;

color1 = Color.FromArgb(common, common, common);

bitmap2.SetPixel(i, j, color1);
}
}

pictureBox2.Image = bitmap2;

Comments or Responses

Login to post response