用C#做图片浏览器

2010-08-28 10:49:35来源:西部e网作者:

      用C#作图片浏览器还是相当方便的,或者说C#用来开发winform还是相当强大的,撇去性能不说。做出了一个简单的图片浏览器:

      GDI+自己封装了相当多的功能,使得图形编程比GDI方便了很多,用MFC可能要写的很多代码,用C#只要简单的一些就能实现。下面是过程和部分代码:

      先建一个用来显示图形的form(此处名为picture),并添加代码如下:

    public partial class Picture : Form
    {
        public Image image1;
        public string filename = "";
        public void SetFilename(string filename1)
        {
            this.filename = filename1;
        }

        public Picture()
        {
            InitializeComponent();
            {
                this.components = new System.ComponentModel.Container();
            }
        }      

        protected override void OnPaint(PaintEventArgs e)
        {
            Graphics gp = e.Graphics;
            gp.DrawImageUnscaled(image1, this.AutoScrollPosition);
            base.OnPaint(e);
        }

      picuture 的designer类中,改写Dispose方法如下:

        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
            image1.Dispose();
        }

      建立picture的MDI父窗体MainForm,关键是改写OpenFile方法如下:

 private void OpenFile(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            //定位初始目录
            if (flag==false)
                openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            //设置图片文件类型过滤
            openFileDialog.Filter = " JPEG files (*.jpg)|*.jpg|位图(*.bmp)|*.bmp|GIF files (*.gif)|*.gif|所有文件(*.*)|*.*";
           
            if (openFileDialog.ShowDialog(this) == DialogResult.OK)
            {
                FileName = openFileDialog.FileName;

                //实例化picture Form
                Picture childForm = new Picture();
                childForm.MdiParent = this;
                childForm.SetFilename(FileName);
                childForm.image1 = Image.FromFile(FileName);
                //childForm.Size = new System.Drawing.Size(800,600);
                childForm.Size = childForm.image1.Size;
                childForm.AutoSize = false;
                childForm.AutoScale = true;
                childForm.AutoScrollMinSize = childForm.image1.Size;
                childForm.Text = FileName;
                //显示图片
                childForm.Show();

                //定位初始目录到当前目录
                string filepath=FileName.Substring( 0,FileName.LastIndexOf(@"\") );
                openFileDialog.InitialDirectory = filepath;
                flag = true;
            }
        }

      这是一个功能很简单的图片浏览器。(许多功能还都需要自己慢慢添加,这只是一个开头和思路。)

关键词:C#

赞助商链接: