在好例子网,分享、交流、成长!
您当前所在位置:首页C# 开发实例C#语言基础 → 图片批量转换工具(利用FreeImage)

图片批量转换工具(利用FreeImage)

C#语言基础

下载此实例
  • 开发语言:C#
  • 实例大小:2.53M
  • 下载次数:26
  • 浏览次数:448
  • 发布时间:2015-10-05
  • 实例类别:C#语言基础
  • 发 布 人:风靡义磊
  • 文件格式:.zip
  • 所需积分:2
 相关标签: 图片 ee 转换 工具

实例介绍

【实例简介】

图片批量转换工具(利用FreeImage),实现大部分图片格式的互相转换。

【实例截图】

【核心代码】

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Drawing.Imaging;
using System.Threading;
using System.Runtime.Serialization.Formatters.Binary;

namespace Pictures_Converter
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            w = new Welcome();
            w.Show();
            InitializeComponent();
        }
        Welcome w;
        Preview p;
        volatile bool stop = false;
        MsBox m = new MsBox();
        Option op = new Option();
        MsBox2 m2 = new MsBox2();
        private void Form1_Load(object sender, EventArgs e)
        {
            
            this.listView1.ListViewItemSorter = new ListViewColumnSorter();
            this.listView1.ColumnClick  = new ColumnClickEventHandler(ListViewHelper.ListView_ColumnClick);
            this.FormClosing  = new FormClosingEventHandler(Form1_FormClosing);
            FileStream cfg=null;
            BinaryReader config = null;
            if (!File.Exists("FreeImageNET.dll") || !File.Exists("FreeImage.dll"))
            {
                MessageBox.Show("FreeImage库文件丢失,请重新下载!", "错误");
                this.Close();
            }
            if(File.Exists("Pictures Converter.cfg"))
            {
                try
                {
                    cfg = new FileStream("Pictures Converter.cfg", FileMode.Open);
                    config = new BinaryReader(cfg);
                    BinaryFormatter format = new BinaryFormatter();
                    List<ListViewItem> items = (List<ListViewItem>)format.Deserialize(cfg);
                    ListViewItem[] lists=items.ToArray();
                    listView1.Items.AddRange(lists);
                    comboBox1.SelectedIndex = config.ReadInt32();
                    textBox1.Text = config.ReadString();
                    openFileDialog1.InitialDirectory = config.ReadString();
                }
                catch { }
                finally
                {
                    try
                    {
                        config.Close();
                        cfg.Close();
                    }
                    catch { };
                }
            }
            Thread.Sleep(500);
            w.Dispose();
            
        }

        void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                FileStream cfg = new FileStream("Pictures Converter.cfg", FileMode.Create);
                BinaryWriter config = new BinaryWriter(cfg);
                BinaryFormatter format = new BinaryFormatter();
                List<ListViewItem> items = new List<ListViewItem>(listView1.Items.Count);
                foreach (ListViewItem l in listView1.Items)
                {
                    items.Add(l);
                    if (items.Count > 4999) break;
                }
                format.Serialize(cfg, items);
                config.Write(comboBox1.SelectedIndex);
                config.Write(textBox1.Text);
                config.Write(Path.GetFullPath(openFileDialog1.FileNames[0]));
            }
            catch { }

        }

        public delegate void commbdelegate(int i,  bool success, string errmsg);
        public void commb(int i, bool success, string errmsg)
        {
            if (success)
            {
                listView1.Items[i].SubItems[2].Text = "已转换";
                listView1.Items[i].SubItems[2].ForeColor = Color.Green;
            }
            else
            {
                textBox2.AppendText(errmsg);
                listView1.Items[i].SubItems[2].Text = "转换失败";
                listView1.Items[i].SubItems[2].ForeColor = Color.Red;
            }
            if (listView1.Items.Count > i 1)
            {
                listView1.Items[i   1].SubItems[2].Text = "正在转换";
                listView1.Items[i   1].SubItems[2].ForeColor = Color.Blue;
            }
        }
        private void ConvertFile(object o)
        {
            List<string> source = (List<string>)o;
            string dest = source[source.Count - 2];
            if (dest[dest.Length - 1] != '\\') dest  = '\\';
            string item = source[source.Count - 1];
            int i;
            string destfile = null;
            for ( i= 0; i < source.Count - 2; i  ) //注意最后是textbox1,n,item
            {
                if (stop) break;
                this.Invoke(new Action(() =>
                {
                    if (为转换的文件编号ToolStripMenuItem.Checked)
                    {
                        destfile = dest   i.ToString()   "."   item;
                    }
                    else
                    {
                        destfile = dest   Path.GetFileNameWithoutExtension(source[i])   "."   item;
                    }
                    progressBar1.Increment(1);
                    return;
                }));
                Bitmap bmp = FreeImageToBitmap.LoadImageFormFreeImage(source[i]);
                op.SetBitMap(ref bmp);
                this.Invoke(new Action(() =>
                {
                    progressBar1.Increment(1);
                    return;
                }));
                if (bmp != null)
                {
                    if (FreeImageToBitmap.SaveImageFromBitmap(bmp,destfile,item))
                    {
                        this.Invoke(new commbdelegate(commb), i,  true,null);
                        
                    }
                    else
                    {
                        this.Invoke(new commbdelegate(commb), i,  false,"\t保存到" destfile "失败。\r\n\r\n");
                    }
                    bmp.Dispose();
                    
                }
                else
                {
                    this.Invoke(new commbdelegate(commb), i,  false,"\t读取" source[i] "失败。\r\n\r\n");
                }
            }
            this.Invoke(new Action(() =>
            {
                if (listView1.Items.Count > i )
                {
                    listView1.Items[i].SubItems[2].Text = "未转换";
                    listView1.Items[i].SubItems[2].ForeColor = Color.Black;
                }
                foreach (Control c in this.Controls)
                {
                    if (c is Button || c is ComboBox) c.Enabled = true;
                }
                textBox1.Enabled = true;
                button7.Enabled = false;
                progressBar1.Value = 0;
                if (stop) textBox2.AppendText("用户停止转换。\r\n\r\n");
                else
                {
                    textBox2.AppendText("转换完毕。\r\n\r\n");
                    if (删除源文件ToolStripMenuItem1.Checked)
                    {
                        RemoveFiles();
                    }

                    if (自动关机ToolStripMenuItem.Checked)
                    {
                        try
                        {
                            System.Diagnostics.Process.Start(System.Environment.GetEnvironmentVariable("windir")
                                  @"\system32\Shutdown", "/s /t 30 /c \"转换已经完成,30秒后系统将关机。\"");
                            this.Close();
                        }
                        catch
                        {
                            MessageBox.Show("自动关机失败。", "错误");
                        }
                    }
                }
                stop = false;
                contextMenuStrip1.Enabled = true;
            }));
            
        }

        private void button1_Click(object sender, EventArgs e)   //开始转换
        {
            if (listView1.Items.Count == 0)
            {
                MessageBox.Show("请先添加要转换的文件!", "提示");
                return;
            }
            if (textBox1.Text == "" || textBox1.Text == null)
            {
                MessageBox.Show("请先选择转换后文件所在目录!", "提示");
                return;
            }
            if (comboBox1.SelectedIndex < 0 || comboBox1.SelectedIndex > 12)
            {
                MessageBox.Show("请先选择目标格式!", "提示");
                return;
            }
            progressBar1.Maximum = 2*listView1.Items.Count - 1;
            foreach (Control c in this.Controls)
            {
                if (c is Button || c is ComboBox) c.Enabled = false;
            }
            contextMenuStrip1.Enabled = false;
            textBox1.Enabled = false;
            button7.Enabled = true;
            int n = comboBox1.SelectedIndex;
            string item = comboBox1.SelectedItem.ToString();
            List<string> Files = new List<string>(10);
            for (int i = 0; i < listView1.Items.Count; i  )
            {
                listView1.Items[i].SubItems[2].Text = "未转换";
                listView1.Items[i].SubItems[2].ForeColor = Color.Black;
                Files.Add(listView1.Items[i].SubItems[3].Text);
            }
            Files.Add(textBox1.Text);
            Files.Add(item);
            textBox2.AppendText(System.DateTime.Now.ToString() "\r\n\r\n");
            Thread loop = new Thread(new ParameterizedThreadStart(ConvertFile));
            loop.IsBackground = true;
            loop.Start(Files);

        }

        private void button6_Click(object sender, EventArgs e)  //选择
        {
            folderBrowserDialog1.SelectedPath = textBox1.Text;
            if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
            {
                textBox1.Text = folderBrowserDialog1.SelectedPath;
            }
        }

        private void AddFile(string[] files)
        {
            int option=0;
            List<ListViewItem> items = new List<ListViewItem>(files.Length);
            foreach (string file in files)
            {
                int i = listView1.Items.Count;
                if (i   items.Count > 99999)
                {
                    MessageBox.Show("列表中项太多!只加载了一部分。", "提示");
                    break;
                }
                if (!File.Exists(file)) continue;
                else if (listView1.Items.Count < 100)
                {
                    for (i = 0; i < listView1.Items.Count; i  )
                    {
                        if (listView1.Items[i].SubItems[3].Text == file) break;
                    }
                }
                
                if (i != listView1.Items.Count)
                {
                    if (option < 2)
                    {
                        m.MessageText = "文件"   file   "已经存在,是否需要重新转换?";
                        m.ShowDialog();
                        option = m.Option;
                    }
                    if (option == 0 || option == 2)
                    {
                        listView1.Items[i].SubItems[2].Text = "未转换";
                        listView1.Items[i].SubItems[2].ForeColor = Color.Black;
                    }
                }
                else
                {
                    string filename = Path.GetFileNameWithoutExtension(file);
                    string ext = Path.GetExtension(file);
                    if (ext.Length > 0) ext = ext.Substring(1);
                    ListViewItem l = new ListViewItem(filename);
                    l.SubItems.AddRange(new string[] { ext, "未转换", file });
                    l.UseItemStyleForSubItems = false;
                    items.Add(l);

                }
            }
            listView1.Items.AddRange(items.ToArray());
        }

        private void button7_Click(object sender, EventArgs e)
        {
            stop = true;
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)  //预览
        {
            if (checkBox1.Checked)
            {
                p = new Preview(checkBox1);
                ListViewNF.SelectedListViewItemCollection list = listView1.SelectedItems;
                p.Show();
                if (list.Count == 1)
                {
                    ListViewItem l = list[0];
                    string file = l.SubItems[3].Text;
                    Thread show = new Thread(new ParameterizedThreadStart(ShowPicture));
                    show.IsBackground = true;
                    show.Start(file);
                }
                else if(list.Count==0)
                    p.ShowPicture(null,null);
                
            }
            else
            {
                p.Close();
            }
        }

        private void listView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            ListViewNF.SelectedListViewItemCollection list = listView1.SelectedItems;
            if (checkBox1.Checked)
            {
                if (list.Count == 1)
                {
                    ListViewItem l = list[0];
                    string file = l.SubItems[3].Text;
                    Thread show = new Thread(new ParameterizedThreadStart(ShowPicture));
                    show.IsBackground = true;
                    show.Start(file);
                }
                else if (list.Count == 0)
                    p.ShowPicture(null,null);
            }
        }

        private void ShowPicture(object o)
        {
            string file = (string)o;
            p.ShowPicture(file,op);
        }

        private void Form1_DragDrop(object sender, DragEventArgs e)
        {
            string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
            AddFile(files);
        }

        private void Form1_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
                e.Effect = DragDropEffects.Link;
            else e.Effect = DragDropEffects.None; 
        }

        private void listView1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete) 删除ToolStripMenuItem_Click(null, null);
        }

        private void textBox2_KeyUp(object sender, KeyEventArgs e)  //清除
        {
            if (e.KeyCode == Keys.Back)
            {
                textBox2.Text = @"本程序基于FreeImage库,支持常见的多种格式批量转换。

快捷键:Delete-删除列表选定项,BackSpace-清除转换记录。 

有什么意见或建议,欢迎联系作者:QQ-597013296。

";
            }
        }

        private void 删除ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ListViewNF.SelectedIndexCollection selected = listView1.SelectedIndices;
            int i = selected.Count - 1;
            listView1.BeginUpdate();
            for (; i >= 0; i--)
            {
                listView1.Items.RemoveAt(selected[i]);
            }
            listView1.EndUpdate();
        }

        private void 清空ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            listView1.Items.Clear();
        }

        private void 添加AToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                string[] files = openFileDialog1.FileNames;
                AddFile(files);
            }
        }

        private void 删除已转换项ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            listView1.BeginUpdate();
            for (int i = listView1.Items.Count - 1; i >= 0; i--)
            {
                if (listView1.Items[i].SubItems[2].Text == "已转换")
                {
                    listView1.Items.RemoveAt(i);
                }
            }
            listView1.EndUpdate();
        }

        private void 添加文件夹ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (folderBrowserDialog2.ShowDialog() == DialogResult.OK)
            {
                DirectoryInfo d= new DirectoryInfo(folderBrowserDialog2.SelectedPath);
                m2.ShowDialog();
                this.Enabled=false;
                this.Text="正在搜寻文件...";
                string[] s = null;
                if (m2.checkBox2.Checked)
                {
                     s = new string[]{"*.BMP","*.ICO","*.JPEG","JPG","*.JNG",
                        "*.KOALA","*.LBM","*.IFF","*.MNG","*.PBM","*.PBMRAW","*.PCD",
                        "*.PCX","*.PGM","*.PGMRAW","*.PNG","*.PPM","*.PPMRAW","*.RAS",
                        "*.TARGA","*.TIFF","*.WBMP","*.PSD","*.CUT","*.XBM","*.XPM",
                        "*.DDS","*.GIF","*.HDR","*.FAXG3","*.SGI","*.EXR","*.J2K",
                        "*.JP2","*.PFM","*.PICT","*.RAW"};
                }
                else
                {
                     s = new string[] { "*.*" };
                }
                try
                {
                    FileInfo[] fi = null;
                    List<string> files = new List<string>();
                    if (m2.checkBox1.Checked)
                    {
                        GetFiles(ref files, d, s);
                    }
                    else
                    {
                        fi = s.SelectMany(i => d.GetFiles(i, SearchOption.TopDirectoryOnly)).Distinct().ToArray();
                        foreach (FileInfo f in fi)
                        {
                            files.Add(f.FullName);
                            if (files.Count > 99999) break;
                        }
                    }
                    this.Text = "正在加载文件...";
                    AddFile(files.ToArray());
                }
                catch
                {
                }
                this.Text = "图片批量转换器";
                this.Enabled = true;
            }
        }


        private void GetFiles(ref List<string> files,DirectoryInfo di, string[] pattern)   //遇到问题要跳过,而不是throw
        {
            if (files.Count > 99999) return;
            try
            {
                FileInfo[] fi = pattern.SelectMany(i => di.GetFiles(i)).Distinct().ToArray();
                foreach (FileInfo f in fi)
                {
                    files.Add(f.FullName);
                }
            }
            catch { }

            try
            {
                DirectoryInfo[] dis = di.GetDirectories();
                foreach (DirectoryInfo d in dis)
                {
                    GetFiles(ref files, d, pattern);
                }
            }
            catch { }
        }

        private void 统一转换选项OToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (op.ShowDialog() == DialogResult.OK && checkBox1.Checked)
            {
                p.RefreshPicture(op);
            }
        }

        private void 删除源文件ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("您确定要永久删除选中文件吗?", "警告", MessageBoxButtons.OKCancel) == DialogResult.OK)
            {
                ListViewNF.SelectedIndexCollection selected = listView1.SelectedIndices;
                RemoveFiles(selected);
            }
        }

        private void RemoveFiles(ListViewNF.SelectedIndexCollection selected)   //删除指定项目 源文件
        {
            int i = selected.Count - 1;
            listView1.BeginUpdate();
            for (; i >= 0; i--)
            {
                string file = listView1.Items[selected[i]].SubItems[3].Text;
                try
                {
                    File.Delete(file);
                    listView1.Items.RemoveAt(selected[i]);
                }
                catch
                { };
            }
            listView1.EndUpdate();
        }

        private void RemoveFiles()  //删除已转换项目
        {
            listView1.BeginUpdate();
            foreach (ListViewItem l in listView1.Items)
            {
                if (l.SubItems[2].Text == "已转换")
                {
                    string file = l.SubItems[3].Text;
                    try
                    {
                        File.Delete(file);
                        listView1.Items.Remove(l);
                    }
                    catch { }
                }
            }
            listView1.EndUpdate();
        }

        private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)  //展开菜单
        {
            if (listView1.SelectedIndices.Count == 0)
            {
                删除ToolStripMenuItem.Enabled = false;
                删除源文件ToolStripMenuItem.Enabled = false;
            }
            else
            {
                删除ToolStripMenuItem.Enabled = true;
                删除源文件ToolStripMenuItem.Enabled = true;
            }
        }

        private void 检查更新ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Version ver = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
            textBox2.AppendText("当前版本:" ver.Major "." ver.Minor  "\r\n\r\n");
            BeginUpdate u = new BeginUpdate();
            u.checkUpdate();
        }

        private void 打开目标文件夹ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                System.Diagnostics.Process.Start("explorer.exe", textBox1.Text);

            }
            catch
            {
                MessageBox.Show("打开失败!", "错误");
            }
        }

    }
}

标签: 图片 ee 转换 工具

实例下载地址

图片批量转换工具(利用FreeImage)

不能下载?内容有错? 点击这里报错 + 投诉 + 提问

好例子网口号:伸出你的我的手 — 分享

网友评论

发表评论

(您的评论需要经过审核才能显示)

查看所有0条评论>>

小贴士

感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。

  • 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
  • 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
  • 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
  • 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。

关于好例子网

本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明

;
报警