本文主要是介绍读入图像文件并显示【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);
}
}
}
}
结果如图:
需要注意的问题:
在写好paint事件后,需要在窗体的事件中进行关联,开始没有关联,所以总是不能显示。
如下:
这篇关于读入图像文件并显示【C#图像处理学习笔记】的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!