C#图像处理的多种方法

2020-01-05 09:36:03王振洲

本文实例为大家分享了C#图像处理的具体代码,供大家参考,具体内容如下

(1)在Form1窗体中的PictureBox1控件中显示通过OpenFileDialog指定的图像文件内容。

将SizeMode设置成StretchImage


private void 打开ToolStripMenuItem_Click(object sender, EventArgs e)
    {
      OpenFileDialog open = new OpenFileDialog();
      open.Filter = "所有文件|*.*";
      if (open.ShowDialog() == DialogResult.OK)
      {
        Bitmap im = new Bitmap(open.FileName);
        pictureBox1.Image = im;
        //pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
      }
    }

(2)编制一个图像格式转换的应用程序,实现BMP图像与JPEG图像的格式转换。


private void bMPToolStripMenuItem_Click(object sender, EventArgs e)
    {
      Bitmap box = new Bitmap(pictureBox1.Image);
      SaveFileDialog sv1 = new SaveFileDialog();
      sv1.Filter = "bmp|*.bmp";
      sv1.ShowDialog();
      string str = sv1.FileName;
      box.Save(str, System.Drawing.Imaging.ImageFormat.Bmp);
    }
 
private void jPEGToolStripMenuItem_Click(object sender, EventArgs e)
    {
      Bitmap box = new Bitmap(pictureBox1.Image);
      SaveFileDialog sv1 = new SaveFileDialog();
      sv1.Filter = "jpeg文件|*.jpeg";
      sv1.ShowDialog();
      string str = sv1.FileName;
      box.Save(str, System.Drawing.Imaging.ImageFormat.Jpeg);
    }

(3)在窗体中添加两个PictureBox,然后利用OpenFileDialog控件选择一彩色图像文件并在pictureBox1中加载,然后将这一彩色图像转换为灰度图像,并在pictureBox2中进行显示,将此图像保存为a.bmp。


private void 灰度ToolStripMenuItem_Click(object sender, EventArgs e)
    {
      pictureBox2.SizeMode = PictureBoxSizeMode.StretchImage;
      Color c = new Color();
      Bitmap b1 = new Bitmap(pictureBox1.Image);
      int rr, gg, bb, cc;
      for (int i = 0; i < pictureBox1.Image.Width; i++) 
      {
        for (int j = 0; j < pictureBox1.Image.Height; j++)
        {
          c = b1.GetPixel(i, j);
          rr = c.R;
          gg = c.G;
          bb = c.B;
          cc = (int)((rr + gg + bb) / 3);
          if (cc < 0) cc = 0;
          if (cc > 255) cc = 255;
          Color nc = Color.FromArgb(cc, cc, cc);
          b1.SetPixel(i, j, nc);
        }
      }
      pictureBox2.Refresh();
      pictureBox2.Image = b1;
    }
private void 灰度图像存储ToolStripMenuItem_Click(object sender, EventArgs e)
    {
 
      if (pictureBox2.Image != null)
      {
        Bitmap box = new Bitmap(pictureBox2.Image);
        SaveFileDialog sv1 = new SaveFileDialog();
        sv1.Filter = "bmp文件|*.bmp";
        sv1.ShowDialog();
        string str = sv1.FileName;
        box.Save(str, System.Drawing.Imaging.ImageFormat.Bmp);
        //pictureBox2.SizeMode = PictureBoxSizeMode.StretchImage;
      }
      else MessageBox.Show("没有生成灰度图像");
    }