观看 陈广 老师视频做的图像管理器,代码打包,给需要的朋友。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace 图片管理器
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }
        private string path = Application.StartupPath + "\\图片目录";
        private void MainForm_Load(object sender, EventArgs e)
        {
            try
            {
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误",
                     MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            DirectoryInfo dir = new DirectoryInfo(path);
            foreach (DirectoryInfo d in dir.GetDirectories())//获取dir中的目录
            {
                Folder folder = new Folder(Application.StartupPath,d.Name);
                lstFolder.Items.Add(folder);//这样的话lstFolder中显示的可不是图片目录中的子目录
                 //lstFolder.Items.Add(folder.Name);

            }
        }


        private void tsbtnCreateFolder_Click(object sender, EventArgs e)
        {
            FrmCreateFolder frmCreateFolder = new FrmCreateFolder(this.lstFolder);
            try
            {
                frmCreateFolder.ShowDialog(this);
            }
            finally
            {
                frmCreateFolder.Dispose();
            }
        }

        private void tsbtnLoad_Click(object sender, EventArgs e)
        {
            FrmLoadPic frmLoadPic = new FrmLoadPic(this.lstFolder, this.statusStrip1);
            try
            {
                if (frmLoadPic.ShowDialog(this) == DialogResult.OK)
                {
                    //LoadToListView();
                }
            }
            finally
            {
                frmLoadPic.Dispose();//销毁窗体
            }
        }

       
       
    }
}

 

    陈老师c#讲得确实很好,参照视频写的图像管理器运行成功。分享出来,方便大家参考。

PicInfo类:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Text;
 4 using System.IO;
 5 
 6 namespace 图片管理器
 7 {
 8     class PicInfo
 9     {
10         private string _fullName;//原文件的全路径名称
11         private string _nameNoExtension;//更改后的名称
12         public PicInfo (string path)
13         {
14             _fullName = path;
15             _nameNoExtension = Path.GetFileNameWithoutExtension(path);
16         }
17         //需要通过属性对私有成员变量进行修改
18         public string NameNoExtension //属性
19         {
20             get
21             {
22                 return _nameNoExtension;
23             }
24             set
25             {
26                 if (value != "" && value.IndexOf('.') == -1)//如果在 SortedList 中找到 value,则为 value 的第一个匹配项的从零开始的索引;否则为 -1。
27                //也就是说没有_nameNoExtension中无'.',这时_nameNoExtensions是没有后缀名的
28                 {
29                     _nameNoExtension = value;
30                 }
31             }
32         }
33         public string FullName//属性
34         {
35             get
36             {
37                 return _fullName;
38             }
39             set
40             {
41                 _fullName = value;
42             }
43         }
44         //获得文件后缀名的方法
45         public string GetExtension()
46         {
47             return Path.GetExtension(_fullName);
48         }
49         public static bool IsImage(string path) //判断文件是否为图像,静态方法占用一份空间,不用像实例方法一样,每创建一个对象都要创建相应的空间
50         {
51             // *.BMP;*.JPG;*.GIF;*.jpeg;*.ico
52             string ext = Path.GetExtension(path).ToUpper();
53             if (ext == ".BMP" || ext == ".JPG" || ext == ".GIF"
54                  || ext ==".JPEG" || ext == ".ICO")
55             {
56                 return true;//该文件是图像类型
57             }
58             else
59             {
60                 return false;
61             }
62         }
63 
64     }
65 }

Folder类:

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.IO;
using System.Drawing;

namespace 图片管理器
{
    class Folder
    {
        private string _name;//目录名称,文件夹名称
        private bool _isLoaded;//是否已经把缩略图载入内存
        private string _sourcePath;//图像存放的路径
        private string _thumbnailPath;//缩略图的路径
        public Hashtable bmps;//用于在内存中保存图像的缩略图,hashtable有一个键(存放图像名称)和值(存放图像的缩略图)。
        public Folder(string exePath,string name)
        {
            _name = name;
            _sourcePath = exePath + "\\图片目录\\" + name;
            _thumbnailPath = exePath + "\\缓存目录\\" + name;
            _isLoaded = false;
            if (!Directory.Exists(_sourcePath))
            {
                Directory.CreateDirectory(_sourcePath);

            }
            if (!Directory.Exists(_thumbnailPath))
            {
                Directory.CreateDirectory(_thumbnailPath);
            }
        }

        public bool IsLoaded //只读属性
        {
            get 
            {
                return _isLoaded;
            }
        }
        public string Name //只读属性,表示文件夹名称
        {
            get 
            {
                return _name;
            }
        }
        public string GetSourcePath()//获得源路径,也可以声明为属性
        {
            return _sourcePath;
        }
        public string GetThubnailPath()//获得缩略图存放路径,也可以声明为属性
        {
            return _thumbnailPath;
        }
        public Bitmap GetThubnail(string sourceName)// 通过图像名称获取相应的缩略图
        {
            return (Bitmap)bmps[sourceName];
        }
        public Bitmap GetImage(string aName)  // 通过图像名称获取相应的图像
        {
            Bitmap bmp = new Bitmap(_sourcePath + "\\" + aName);
            return bmp;
        }
        public void LoadImage()//用于把目录中所有缩略图载入到内存中
        {
            if (bmps == null)
            {
                bmps = new Hashtable();
            }
            foreach (string sourceFile in Directory.GetFiles(_sourcePath))
            {
                if (!PicInfo.IsImage(sourceFile))//调用PicInfo类的静态方法IsImage方法,判断文件是否是图像文件
                {
                    continue;
                }
                string picName = Path.GetFileNameWithoutExtension(sourceFile) + ".BMP";
                string thumbailFile = _thumbnailPath + "\\" + picName;
                if (!File.Exists(thumbailFile))//如果缩略图不存在,创建缩略图
                {
                    CreateThumbnail(sourceFile, thumbailFile);
                }

                bmps.Add(Path.GetFileName(sourceFile), new Bitmap(thumbailFile));
            }
            _isLoaded = true;//通过_isLoaded变量标志目录下的所有缩略图都载入到目录中
        }
        private bool ThumbnailCallback()//CreaeThumbail方法需要调用
        {
            return false;
        }
        public void Add(string aName)
        {
            string picName = Path.GetFileNameWithoutExtension(aName) + ".BMP";
            string sourceFile = _sourcePath + "\\" + aName;
            string thumbnailFile = _thumbnailPath + "\\" + picName;
            CreateThumbnail(sourceFile, thumbnailFile);
            bmps.Add(Path.GetFileName(sourceFile), new Bitmap(thumbnailFile));
        }
        private void CreateThumbnail(string source,string dest) //创建缩略图
        {
            Image.GetThumbnailImageAbort myCallback =
                 new Image.GetThumbnailImageAbort(ThumbnailCallback);
            Bitmap bmp = new Bitmap(source);
            int x = bmp.Width;
            int y = bmp.Height;
            try
            {
                if ( x > 100 || y > 100)
                {
                    float scale = (x > y) ? (x / 100F) : (y / 100F);
                    Image aThumbnail =
                        bmp.GetThumbnailImage((int)(x / scale), (int)(y / scale), myCallback,
                         IntPtr.Zero);
                    aThumbnail.Save(dest);
                }
                else
                {
                    bmp.Save(dest);
                }
            }
            catch (Exception ex )
            {
                throw ex;
            }
            finally
            {
                bmp.Dispose();//释放由System.Drawing.Image使用的所有资源

            }
        }
        //重写ToString()方法
        public override string ToString()
        {
           // return base.ToString();//这个是没有重写的
            return _name;//这个是重写的,如果没有重写,在lstFolder.Items.Add(folder)中将无法正确显示子目录;
            //这是因为lstFolder.Items.Add(folder)的参数为字符串,folder对象需要隐式转换为string,即调用ToString()方法。
        }


    }
}

 

FrmCreateFolder类:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.ComponentModel;
 4 using System.Data;
 5 using System.Drawing;
 6 using System.Text;
 7 using System.Windows.Forms;
 8 using System.IO;
 9 
10 namespace 图片管理器
11 {
12     public partial class FrmCreateFolder : Form
13     {
14         public FrmCreateFolder()
15         {
16             InitializeComponent();
17         }
18 
19         public FrmCreateFolder(ListBox lst)//通过构造函数调用主窗体的lstFolder
20         {
21             InitializeComponent();
22             lstFolder = lst;
23         }
24         private ListBox lstFolder;
25         private void btnCancel_Click(object sender, EventArgs e)
26         {
27             this.Close();//关闭窗体
28 
29         }
30 
31         private void btnOk_Click(object sender, EventArgs e)
32         {
33             if (txtFolderName.Text == "")
34             {
35                 MessageBox.Show("请在文本框中输入要新建的目录名称", "消息",
36                     MessageBoxButtons.OK, MessageBoxIcon.Hand);
37                 return;
38             }
39             try
40             {
41                 string path = Application.StartupPath + "\\图片目录\\" +
42                     txtFolderName.Text;
43                // MessageBox.Show(path);
44                 if (Directory.Exists(path))
45                 {
46                     MessageBox.Show("" + txtFolderName.AcceptsReturn + "" +
47                         "目录已经存在,请输入另一个名称!",
48                         "消息对话框", MessageBoxButtons.OK, MessageBoxIcon.Error);
49                     return;
50                 }
51 
52                 Directory.CreateDirectory(path);//建立目录
53                
54                // lstFolder.Items.Add(txtFolderName.Text);// 这个是以前的代码
55                 //现在的是Folder对象,添加的类型的也是items add 的也是folder类型
56                 Folder folder = new Folder(Application.StartupPath, txtFolderName.Text);
57                 lstFolder.Items.Add(folder);//folder隐式调用其ToString()方法
58 
59             }
60             catch (Exception ex)
61             {
62                 MessageBox.Show(ex.Message, "错误",
63                     MessageBoxButtons.OK, MessageBoxIcon.Error);
64                 return;
65 
66             }
67             Close();//运行成功的话,关闭窗口。
68         }
69     }
70 }
  1 using System;
  2 using System.Collections.Generic;
  3 using System.ComponentModel;
  4 using System.Data;
  5 using System.Drawing;
  6 using System.Text;
  7 using System.Windows.Forms;
  8 using System.IO;
  9 using System.Collections;
 10 
 11 namespace 图片管理器
 12 {
 13     public partial class FrmLoadPic : Form
 14     {
 15         public FrmLoadPic()
 16         {
 17             InitializeComponent();
 18         }
 19         //重载的构造函数,参数方便对主窗体的lstFolder和StatusStrip控件进行控制
 20         public FrmLoadPic(ListBox lst, StatusStrip sta)
 21         {
 22             InitializeComponent();//初始化函数
 23             lstFolder = lst;
 24             staMsg = sta;
 25             openFileDialogSelPic.Filter = "图像文件(*.BMP,*.JPG,*.GIF;" +
 26             "*.jpeg;*.ico)|*.BMP;*.JPG;*.GIF;*.jpeg;*.ico";
 27             
 28         }
 29         private ListBox lstFolder;//定义私有的ListBox类型的对象。
 30         private StatusStrip staMsg;
 31 
 32         private void FrmLoadPic_Load(object sender, EventArgs e)
 33         {
 34             foreach (object o in lstFolder.Items)
 35             {
 36                 cbFolder.Items.Add(o);
 37             }
 38             if (lstFolder.SelectedItems.Count !=0)
 39             {
 40                 cbFolder.SelectedIndex = lstFolder.SelectedIndex;
 41             }
 42             else
 43             {
 44                 cbFolder.SelectedIndex = 0;
 45             }
 46         }
 47 
 48         private void btnSelPic_Click(object sender, EventArgs e)
 49         {
 50             if (openFileDialogSelPic.ShowDialog() == DialogResult.OK)
 51             {
 52                 foreach (string s in openFileDialogSelPic.FileNames)
 53                 {
 54                     if (!chklsPics.Items.Contains(s) && PicInfo.IsImage(s))//使用PicInfo类的静态方法IsImage,判断文件是否是图像文件
 55 
 56                     {
 57                         PicInfo picInfo = new PicInfo(s);
 58                         chklsPics.Items.Add(picInfo, true);
 59                     }
 60                 }
 61             }
 62         }
 63 
 64         private void chklsPics_SelectedIndexChanged(object sender, EventArgs e)
 65         {
 66             txtPicName.Text = ((PicInfo)chklsPics.SelectedItem).NameNoExtension;//把chklsPics中的Item项目强制类型转换为原来的PicInfo类型
 67         }
 68 
 69         private void btnUpdateName_Click(object sender, EventArgs e)
 70         {
 71             if (chklsPics.SelectedItems.Count !=0)
 72             {
 73                 ((PicInfo)chklsPics.SelectedItem).NameNoExtension = txtPicName.Text;
 74             }
 75         }
 76 
 77         private void btnOK_Click(object sender, EventArgs e)
 78         {
 79             if (chklsPics.Items.Count ==0)
 80             {
 81                 return;
 82             }
 83             ArrayList names = new ArrayList();//存放目的文件夹中已有文件名称
 84             Folder folder = (Folder)cbFolder.SelectedItem;
 85             if (!folder.IsLoaded)
 86             {
 87                 folder.LoadImage();
 88             }
 89             string path = folder.GetSourcePath();
 90             names.AddRange(Directory.GetFiles(path));
 91             for ( int i = 0; i < names.Count; i++)
 92             {
 93                 names[i] =
 94                      Path.GetFileNameWithoutExtension((string)names[i]).ToUpper();
 95             }
 96             names.Sort();
 97             ToolStripProgressBar bar = (ToolStripProgressBar)staMsg.Items[0];
 98             bar.Visible = true;
 99             this.Cursor = Cursors.WaitCursor;//设置鼠标指针样式
100             try
101             {
102                 int i = 1; //制定图像序号,用于进度条中的进度显示
103                 int count = chklsPics.CheckedItems.Count;
104                 foreach (PicInfo p in chklsPics.CheckedItems)
105                 {
106                     staMsg.Items[1].Text = ""; //清空状态栏文字
107                     string name = InsertAName(p.NameNoExtension,names);
108                     string destFile = path + "\\" + name + p.GetExtension();
109                     File.Copy(p.FullName, destFile); //拷贝图像到图片存储目录中
110                     folder.Add(name + p.GetExtension());
111                     bar.Value = 100 * i / count; //在进度条中显示进度
112                     i++;
113                 }
114             }
115             catch (Exception ex)
116             {
117                 MessageBox.Show(ex.Message, "错误",
118                      MessageBoxButtons.OK, MessageBoxIcon.Error);
119                 return;
120             }
121             finally
122             {
123                 this.Cursor = Cursors.Default;
124                 bar.Visible = false;
125             }
126             int index = lstFolder.FindString(cbFolder.Text);
127             if (lstFolder.SelectedIndex!=index)
128             {
129                 lstFolder.SelectedIndex = index;
130             }
131             this.DialogResult = DialogResult.OK; //可用于关闭模式窗体
132 
133         }
134         private string InsertAName(string aName, ArrayList names)
135         {
136             //在一个名称集合中插入指定的名称
137             int nameExtend = 0; //用于出现相同名称时,在文件后面添加的数字
138             string tempName = aName;//要插入的文件名
139             int namesCount = names.Count;
140             for (int i=0;i < namesCount;i++)
141             {
142                 string name = (string)names[i];
143                 if (tempName.ToUpper().CompareTo(name) == 0) //如果文件同名
144                 {
145                     //在文件名后添加减号和数字零
146                     nameExtend++;
147                     tempName = Path.GetFileNameWithoutExtension(aName)
148                     + "-" + nameExtend.ToString();
149                 }
150                 if (tempName.ToUpper().CompareTo(name) == -1)
151                 {
152                     //如果文件名小于名称集合中的某个名称,则插入
153                     names.Insert(i, tempName);
154                     break;
155                 }
156                 if (i == namesCount - 1)
157                 {
158                     //如果到达名称集合底部,则直接添加。
159                     names.Add(tempName);
160                 }
161             }
162             return tempName;//返回新的文件名
163         }
164     }
165 }

 

 

 

posted on 2012-07-02 21:37  傲视群雄  阅读(648)  评论(0编辑  收藏  举报