C# Exercises

Home AgriMetSoft About Contact

Change to Black and White in WinForms c#

	    
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Pricutre_to_Black_and_White
{
  public partial class Form1 : Form
  {
    int click = 0;
    string fileName;
    public Form1()
    {
      InitializeComponent();
    }

    private void select_pricture_Click(object sender, EventArgs e)
    {

      using (OpenFileDialog ofd = new OpenFileDialog() { Filter = @"JPG|*.jpg|PNG|*.png|BMP|*.bmp" })
      {
        if (ofd.ShowDialog() == DialogResult.OK)
        {
          fileName = ofd.FileName;
          pictureBox1.Image = Image.FromFile(ofd.FileName);
          pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
          click = 0;
        }
      }
    }

    private void black_and_white_Click(object sender, EventArgs e)
    {
      var btm =(Bitmap)Image.FromFile(fileName);
      Bitmap grayScale = new Bitmap(btm.Width, btm.Height);
      for (Int32 y = 0; y < grayScale.Height; y++)
        for (Int32 x = 0; x < grayScale.Width; x++)
        {
          Color c = btm.GetPixel(x, y);
          Int32 gs = (Int32)(c.R + c.G + c.B) / 3;
          //  Int32 gs = (Int32)(c.R * 0.3 + c.G * 0.59 + c.B * 0.11);
          grayScale.SetPixel(x, y, Color.FromArgb(gs, gs, gs));
        }
      pictureBox1.Image = grayScale;
      click = 1;
    }

    private void pictureBox1_Click(object sender, EventArgs e)
    {
      var image = Image.FromFile(fileName);
      if (click % 2 == 0)
      {
        using (Graphics gr = Graphics.FromImage(image)) // SourceImage is a Bitmap object
        {
          var gray_matrix = new float[][] {
        new float[] { 0.299f, 0.299f, 0.299f, 0, 0 },
        new float[] { 0.587f, 0.587f, 0.587f, 0, 0 },
        new float[] { 0.114f, 0.114f, 0.114f, 0, 0 },
        new float[] { 0,   0,   0,   1, 0 },
        new float[] { 0,   0,   0,   0, 1 }
          };

          var ia = new System.Drawing.Imaging.ImageAttributes();
          ia.SetColorMatrix(new System.Drawing.Imaging.ColorMatrix(gray_matrix));
          ia.SetThreshold((float)0.7); // Change this threshold as needed
          var rc = new Rectangle(0, 0, image.Width, image.Height);
          gr.DrawImage(image, rc, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, ia);
          pictureBox1.Image = image;
        }
      }
      else
      {
        pictureBox1.Image = image;
        pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
      }
      click++;
    }
  }
}
		
	 


Download the project of Visual Studio 2013 in DropBox Download


How to Convert Image to Black and White in Windows Forms C#


List of Exercises