• Jpegoptim Tool


    using System;
    using System.Drawing;
    using System.Windows.Forms;
    using System.Diagnostics;
    using System.IO;
    
    namespace JpegoptimTool
    {
        public partial class Compress : Form
        {
            #region [init define var]
            /// <summary>
            /// Define Process 
            /// </summary>
            private Process myProcess;
    
            /// <summary>
            /// Define Stream Writer
            /// </summary>
            private StreamWriter myWriter;
    
            /// <summary>
            /// Define Method Invoker
            /// </summary>
            private MethodInvoker myMethodInvoker;
    
            /// <summary>
            /// Define String Output
            /// </summary>
            private string myCurrentOutput;
            #endregion
    
            #region [Construct Compress]
            public Compress()
            {
                InitializeComponent();
                myCurrentOutput = string.Empty;
                myMethodInvoker = new MethodInvoker(ShowOutput);
                myProcess = new Process();
                myProcess.OutputDataReceived += MyProcessOutputDataReceived;
    
                InitializeControlSize();
            }
    
            /// <summary>
            /// Initialize Control Size
            /// </summary>
            private void InitializeControlSize()
            {
                int count = Controls.Count * 2 + 2;
                float[] factor = new float[count];
                int i = 0;
                factor[i++] = Size.Width;
                factor[i++] = Size.Height;
                foreach (Control ctrl in this.Controls)
                {
                    factor[i++] = ctrl.Location.X / (float)Size.Width;
                    factor[i++] = ctrl.Location.Y / (float)Size.Height;
                    ctrl.Tag = ctrl.Size;
                }
                Tag = factor;
            }
    
            /// <summary>
            /// 每次使用的都是最初始的控件大小,保证准确无误。
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void Compress_Resize(object sender, EventArgs e)
            {
                float[] scale = (float[])Tag;
                int i = 2;
    
                foreach (Control ctrl in this.Controls)
                {
                    ctrl.Left = (int)(Size.Width * scale[i++]);
                    ctrl.Top = (int)(Size.Height * scale[i++]);
                    ctrl.Width = (int)(Size.Width / (float)scale[0] * ((Size)ctrl.Tag).Width);
                    ctrl.Height = (int)(Size.Height / (float)scale[1] * ((Size)ctrl.Tag).Height);
                }
            }
    
            #endregion
    
            #region [My Process OutPut Data Received]
            /// <summary>
            /// My Process OutPut Data Received
            /// </summary>
            /// <param name="sender">Sender</param>
            /// <param name="e">DataReceivedEventArgs</param>
            void MyProcessOutputDataReceived(object sender, DataReceivedEventArgs e)
            {
                myCurrentOutput = e.Data;
                BeginInvoke(myMethodInvoker);
            }
            #endregion
    
            #region [Show Result in OutPut]
            /// <summary>
            /// Show OutPut
            /// </summary>
            private void ShowOutput()
            {
                if (!String.IsNullOrEmpty(myCurrentOutput.Trim()) && !_txtOutput.Text.Contains(myCurrentOutput.Trim()))
                {
                    _txtOutput.Text += @"压缩详细输出结果--" + myCurrentOutput + "\r\n";   
                    _txtOutput.Refresh();
                }
            }
            #endregion
    
            #region [Start Process]
            /// <summary>
            /// Start Process
            /// </summary>
            private void StartProcess()
            {
                ProcessStartInfo processStartInfo = new ProcessStartInfo("cmd.exe");
                processStartInfo.CreateNoWindow = true;
                processStartInfo.RedirectStandardInput = true;
                processStartInfo.RedirectStandardOutput = true;
                processStartInfo.UseShellExecute = false;
    
                myProcess.StartInfo = processStartInfo;
                myProcess.Start();
                myWriter = myProcess.StandardInput;
                myProcess.BeginOutputReadLine();
            }
            #endregion
    
            #region [Select File include Pic And Compress Pic]
            /// <summary>
            /// Compress Image Pic
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void btnSelectFile_Click(object sender, EventArgs e)
            {
                if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
                {
                    if (MessageBox.Show(@"请先备份您要压缩的图片,压缩期间请不要关闭工具。确实要压缩目录" + folderBrowserDialog1.SelectedPath + @"下的所有图片吗?"
                       , "", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        try
                        {
                            labSourceFilePath.Text = folderBrowserDialog1.SelectedPath;
                            if (labSourceFilePath.Text.Trim().Contains(txtCompressPath.Text.Trim()))
                            {
                                MessageBox.Show(@"您选择压缩后文件存放路径和源文件夹重复,为了防止覆盖,请重新选择!", "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            }
                            else
                            {
                                int intSum = 0;
                                txtPerNum_MouseLeave();
                                int intCompressNum =
                                    int.Parse(System.Configuration.ConfigurationManager.AppSettings["CompressPer"].ToString());
                                int.TryParse(txtPerNum.Text.Trim(), out intCompressNum);
                                string[] filearray = Directory.GetFiles(folderBrowserDialog1.SelectedPath, "*.jpg", SearchOption.AllDirectories);
                                if (filearray != null && filearray.Length > 0)
                                {
                                    btnSelectFile.Enabled = false;
                                    compressProgressBar.Visible = true;
                                    compressProgressBar.Minimum = 0;
                                    compressProgressBar.Maximum = filearray.Length;
                                    compressProgressBar.BackColor = Color.Green;
    
                                    StartProcess();
                                    _txtOutput.Text += @"开始压缩您选择的目录" + folderBrowserDialog1.SelectedPath + @"下文件夹中的" + filearray.Length + @"个JPG图片. " + "\r\n";
                                    if (myWriter != null)
                                    {
                                        foreach (var item in filearray)
                                        {
                                            _txtOutput.Text += @"当前压缩图片的路径--" + item + "\r\n";
    
                                            string strAimDir = GenerateDirBySourceDirAndAimDir(item);
    
    
                                            myWriter.WriteLine(Path.Combine(Environment.CurrentDirectory, "jpegoptim.exe") +
                                                                                   @" --strip-com --strip-exif --strip-iptc -m" +
                                                                                   intCompressNum.ToString() +
                                                                                   " -o " + item + " -d " + strAimDir);
                                            compressProgressBar.Value++;
                                            intSum++;
                                        }
                                    }
    
                                }
                                else
                                {
                                    MessageBox.Show(@"文件夹中没有找到要压缩的图片(jpg)!", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                }
                                _txtOutput.Text += @"目录" + folderBrowserDialog1.SelectedPath + @"下压缩选择文件夹下JPG图片完毕!共压缩了:" + intSum.ToString() + @"个图片文件。" + "\r\n";
                                
                                btnSelectFile.Enabled = true;
    
                                if (!string.IsNullOrEmpty(_txtOutput.Text))
                                {
                                    string txtPath = GetTxtPath();
                                    WriteLog(_txtOutput.Text, txtPath);
                                }
                                MessageBox.Show(@"图片压缩完成", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            }
                        }
                        catch (Exception ex)
                        {
                            if (myProcess != null)
                            {
                                myProcess.Close();
                                myProcess.Dispose();
                                myProcess.Kill();
                            }
                            MessageBox.Show(@"压缩失败---" + ex,"", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
    
                    }
                }
            }
    
            /// <summary>
            /// GenerateDir By SourceDir And AimDir
            /// </summary>
            /// <param name="item"></param>
            /// <returns></returns>
            private string GenerateDirBySourceDirAndAimDir(string item)
            {
                string[] f = item.Split('\\');
                string s = string.Empty;
                for (int i = 1; i < f.Length-1; i++)
                {
                    if (!string.IsNullOrEmpty(s))
                    {
                        s += "//";
                    }
                    s += f[i];
                }
                string strP = Path.Combine(txtCompressPath.Text, s);
    
                if(!Directory.Exists(strP))
                {
                    Directory.CreateDirectory(strP);
                }
                return strP.Replace("//","\\");
            }
    
            #endregion
    
            #region [Email] 
            /// <summary>
            /// Email
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private  void linkLabelEmail_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
            {
                Process.Start("mailto:wlong@yintai.com ");
            }
            #endregion
    
            #region [Log]
            /// <summary>
            /// Write Log
            /// </summary>
            private void WriteLog(string strContent, string txtPath)
            {
                using (FileStream fileStream = new FileStream(txtPath, FileMode.Create, FileAccess.ReadWrite))
                {
                    using (StreamWriter sw = new StreamWriter(fileStream))
                    {
                        sw.WriteLine("Start------------------------------" + System.DateTime.Now.ToString() + "-------------------------------Start");
                        sw.WriteLine(strContent);
                        sw.WriteLine("End--------------------------------" + System.DateTime.Now.ToString() + "---------------------------------End");
                        sw.Flush();
                        sw.Close();
                        sw.Dispose();
                        fileStream.Close();
                    }
                }
                
            }
    
            /// <summary>
            /// Get Txt Path
            /// </summary>
            /// <returns></returns>
            private string GetTxtPath()
            {
                string strDir = System.Configuration.ConfigurationManager.AppSettings["Log"].ToString();
                if (!Directory.Exists(strDir))
                {
                   DirectoryInfo d =  Directory.CreateDirectory(strDir);
                }
                string txtPath = strDir + DateTime.Now.ToShortDateString().Replace(@"/", "-") + @".txt";
                if (!File.Exists(txtPath))
                {
                    using (File.Create(txtPath))
                    {
                        FileAttributes fileAttributes = File.GetAttributes(txtPath);
                        if (fileAttributes.ToString().IndexOf("ReadOnly") >= 0)
                        {
                            File.SetAttributes(txtPath, FileAttributes.Archive);
                        }
                    }
                    
                }
                return txtPath;
            }
    
            #endregion
    
            #region [CompressFile Dir]
            /// <summary>
            /// Select Compress Pic File New Dir
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void btnCompressFile_Click(object sender, EventArgs e)
            {
                if (folderBrowserDialog2.ShowDialog() == DialogResult.OK)
                {
                    if (MessageBox.Show(@"请确认选择压缩后存放的文件夹路径为:" + folderBrowserDialog2.SelectedPath, "", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        txtCompressPath.Text = folderBrowserDialog2.SelectedPath;
                        if (!txtCompressPath.Visible)
                        {
                            txtCompressPath.Visible = true;
                            txtCompressPath.ReadOnly = true;
                        }
                    }
                }
            }
            #endregion
    
            #region [Per Num Text Changed]
            /// <summary>
            /// Per Num Changed
            /// </summary>
            private void txtPerNum_MouseLeave()
            {
                int intPer = 95;
                try
                {
                    if (string.IsNullOrEmpty(txtPerNum.Text.Trim()) ||!int.TryParse(txtPerNum.Text.Trim(), out intPer))
                    {
                        MessageBox.Show(@"图片压缩比设置有误请确认,如果不设置将以默认压缩比95进行压缩.", "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }
                catch (Exception)
                {
                    MessageBox.Show(@"系统出现异常,请通过疑问反馈联系我们.", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    throw;
                }
            }
            #endregion
        }
    }
    

     图片压缩工具。

  • 相关阅读:
    Js原型对象理解
    Garbage In Garbage Out
    JournalNode的作用
    SecondaryNameNode 的作用
    Hive Map数据长尾问题
    Hive基本操作
    Hadoop中NameNode的工作机制
    技术架构分析与架构分析
    Sqoop报错Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLTransactionRollbackException: Deadlock found when trying to get lock; try restarting transaction
    项目管理PMP相关
  • 原文地址:https://www.cnblogs.com/Leo_wl/p/2305849.html
Copyright © 2020-2023  润新知