`
isiqi
  • 浏览: 16079621 次
  • 性别: Icon_minigender_1
  • 来自: 济南
社区版块
存档分类
最新评论

读入图像文件并显示【C#图像处理学习笔记】

阅读更多

说明:

该系列读书笔记为《C#数字图像处理算法典型事例》(赵春江 编著,人民邮电出版社,2009)读书笔记。

详细内容,请参考原始图书。

================================================

代码如下:

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

namespace Demo1

{

public partial class Form1 : Form

{

private string curFileName;

private System.Drawing.Bitmap curBitmap;

public Form1()

{

InitializeComponent();

}

private void Form1_Load(object sender, EventArgs e)

{

}

private void open_Click(object sender, EventArgs e)

{

OpenFileDialog opndlg = new OpenFileDialog();

opndlg.Filter = "所有文件|*.bmp;*.pcx;*.png;*.jpg;*.gif;" +

"*.tif;*.ico;*.dcx;*.cgm;*.cdr;*.wmf;*.eps;*.emf;|" +

"位图(*.bmp;*.jpg;*.png;...)|*.bmp;*.pcx;*.png;*.jpg;*.gif;*.tif;*.ico|" +

"矢量图(*.wmf;*.eps;*.emf;...)|*.dcf;*.cgm;*.cdr;*.wmf;*.eps;*.emf";

opndlg.Title = "打开图形文件";

opndlg.ShowHelp = true;

if (opndlg.ShowDialog() == DialogResult.OK)

{

curFileName = opndlg.FileName;

try

{

curBitmap = (Bitmap)Image.FromFile(curFileName);

}

catch (Exception exp)

{

MessageBox.Show(exp.Message);

}

}

Invalidate();

}

private void save_Click(object sender, EventArgs e)

{

if (curBitmap == null)

return;

SaveFileDialog saveDlg = new SaveFileDialog();

saveDlg.Title = "保存为";

saveDlg.OverwritePrompt = true;

saveDlg.Filter = "BMP文件(*.bmp)|*.bmp|" + "Gif文件(*.gif)|*.gif|" +

"JPEG文件(*.jpg)|*.jpg|" + "PNG文件(*.png)|*.png";

saveDlg.ShowHelp = true;

if (saveDlg.ShowDialog() == DialogResult.OK)

{

string fileName = saveDlg.FileName;

string strFilExtn = fileName.Remove(0, fileName.Length - 3);

switch (strFilExtn)

{

case "bmp":

curBitmap.Save(fileName, System.Drawing.Imaging.ImageFormat.Bmp);

break;

case "jpg":

curBitmap.Save(fileName, System.Drawing.Imaging.ImageFormat.Jpeg);

break;

case "gif":

curBitmap.Save(fileName, System.Drawing.Imaging.ImageFormat.Gif);

break;

case "tif":

curBitmap.Save(fileName, System.Drawing.Imaging.ImageFormat.Tiff);

break;

case "png":

curBitmap.Save(fileName, System.Drawing.Imaging.ImageFormat.Png);

break;

default:

break;

}

//设定文件格式,Ctrl+E,D

}

}

private void close_Click(object sender, EventArgs e)

{

this.Close();

}

private void Form1_Paint(object sender, PaintEventArgs e)

{

Graphics g = e.Graphics;

if (curBitmap != null)

{

g.DrawImage(curBitmap, 160, 20, curBitmap.Width, curBitmap.Height);

}

}

}

}

结果如图:

clip_image002

需要注意的问题:

在写好paint事件后,需要在窗体的事件中进行关联,开始没有关联,所以总是不能显示。

如下:

clip_image004

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics