图像的输入和保存

方法(一)、窗体设计时使用图形框对象的Image属性输入

方法(二)、使用“打开文件”对话框输入图像

在窗体上添加一个命令按钮(button1)和一个图形框对象(pictureBox1),双击命令按钮,在响应方法中输入如下代码:

View Code
private void button1_Click(object sender, EventArgs e)
    {
         OpenFileDialog ofdlg = new OpenFileDialog();
         ofdlg.Filter = "BMP File(*.bmp)|*.bmp";
         if (ofdlg.ShowDialog() == DialogResult.OK)
         {
             Bitmap image = new Bitmap(ofdlg.FileName);
             pictureBox1.Image = image;
         }
     }

执行该程序时,使用“打开文件”对话框,选择图像文件,该图像将会被打开,并显示在pictureBox1图像框中。

2.图像的保存

保存图像的步骤如下:

(1)当使用按钮和保存对话框保存文件时,加入保存按钮和PictureBox控件,窗体设计如图7.16所示。

(2)保存命令钮的单击事件的响应函数代码如下:

View Code
private void button2_Click(object sender, EventArgs e)
      {
       string str;
       Bitmap box1 = new Bitmap(pictureBox1.Image);
       SaveFileDialog sfdlg = new SaveFileDialog();
       sfdlg.Filter = "bmp文件(*.BMP)|*.BMP|All File(*.*)|*.*";
       sfdlg.ShowDialog();
       str = sfdlg.FileName;
       box1.Save(str);
     }

3.图像格式的转换

使用Bitmap对象的Save方法,可以把打开的图像保存为不同的文件格式,从而实现图像格式的转换。在上述例子中添加一个命令按钮,双击该命令按钮,编辑其相应代码如下:

View Code
private void button3_Click(object sender, EventArgs e)
{
string str;
        Bitmap box1 = new Bitmap(pictureBox1.Image);
        SaveFileDialog sfdlg = new SaveFileDialog();
        sfdlg.Filter = "bmp文件(*.jpeg)|*.jpeg|All File(*.*)|*.*";
        sfdlg.ShowDialog();
        str = sfdlg.FileName;
box1.Save(str,System.Drawing.Imaging.ImageFormat.Jpeg);
}

Bitmap对象的Save方法中的第二个参数指定了图像保存的格式。

Imaging.ImageFormat支持的格式如表7.9所示:

表7.9 Imaging.ImageFormat支持的格式

名称

说明 

Bmp

获取位图图像格式(BMP)。

Emf

获取增强型Windows图元文件图像格式(EMF)。

Exif

获取可交换图像文件(Exif)格式。

Gif

获取图形交换格式(GIF)图像格式。

Guid

获取表示此ImageForma 对象的Guid结构。

Icon

获取Windows图标图像格式。

Jpeg

获取联合图像专家组(JPEG)图像格式。

MemoryBmp

获取内存位图图像格式。

Png

获取W3C可移植网络图形(PNG)图像格式。

Tiff

获取标签图像文件格式(TIFF)图像格式。

Wmf

获取Windows图元文件(WMF)图像格式。

posted on 2012-07-26 15:29  流星落  阅读(280)  评论(0编辑  收藏  举报

导航