浅谈Visual C#进行图像处理(读取、保存以及对像素的访问)

2019-12-30 12:17:13于丽
本文主要介绍利用C#对图像进行读取、保存以及对像素的访问等操作,介绍的比较简单,希望对初学者有所帮助。  

这里之所以说“浅谈”是因为我这里只是简单的介绍如何使用Visual C#进行图像的读入、保存以及对像素的访问。而不涉及太多的算法。

一、读取图像

在Visual C#中我们可以使用一个Picture Box控件来显示图片,如下:

 

复制代码
private void btnOpenImage_Click(object sender, EventArgs e)
{
    OpenFileDialog ofd = new OpenFileDialog();
    ofd.Filter = "BMP Files(*.bmp)|*.bmp|JPG Files(*.jpg;*.jpeg)|*.jpg;*.jpeg|All Files(*.*)|*.*";
    ofd.CheckFileExists = true;
    ofd.CheckPathExists = true;
    if (ofd.ShowDialog() == DialogResult.OK)
    {
        //pbxShowImage.ImageLocation = ofd.FileName;
        bmp = new Bitmap(ofd.FileName);
        if (bmp==null)
        {
            MessageBox.Show("加载图片失败!", "错误");
            return;
        }
        pbxShowImage.Image = bmp;
        ofd.Dispose();
    }
}

 

其中bmp为类的一个对象:private Bitmap bmp=null;
在使用Bitmap类和BitmapData类之前,需要使用using System.Drawing.Imaging;

二、保存图像

 

复制代码
private void btnSaveImage_Click(object sender, EventArgs e)
{
    if (bmp == null) return;
    SaveFileDialog sfd = new SaveFileDialog();
    sfd.Filter = "BMP Files(*.bmp)|*.bmp|JPG Files(*.jpg;*.jpeg)|*.jpg;*.jpeg|All Files(*.*)|*.*";
    if (sfd.ShowDialog() == DialogResult.OK)
    {
        pbxShowImage.Image.Save(sfd.FileName);
        MessageBox.Show("保存成功!","提示");
        sfd.Dispose();