protected void OnBeforeWritingFile(CrunchResult result)
 {
     if (BeforeWritingFile != null)
     {
         BeforeWritingFile(this, new CruncherEventArgs(result));
     }
 }
예제 #2
0
 protected void OnCompleted(CrunchResult result)
 {
     if (Completed != null)
     {
         Completed(this, new CruncherEventArgs(result));
     }
 }
        /// <summary>
        /// Optimizes the specified file.
        /// </summary>
        /// <param name="fileName">The absolute path to the file.</param>
        /// <exception cref="System.NotImplementedException"></exception>
        public void Optimize(String fileName)
        {
            TryToInitMozjpeg();

            var originalFile = fileName;
            var tempFile     = Path.Combine(Path.GetTempPath(), String.Format("{0}.jpg", Guid.NewGuid().ToString()));

            CompressJpeg(originalFile, tempFile);

            var originalFileSize = (new FileInfo(fileName)).Length;
            var tempFileSize     = (new FileInfo(tempFile)).Length;
            var result           = new CrunchResult(fileName, this.Service)
            {
                SizeBefore   = originalFileSize,
                SizeAfter    = tempFileSize,
                PercentSaved = Math.Round(100 - ((Double)tempFileSize / originalFileSize) * 100, 2)
            };

            File.Delete(tempFile);

            OnBeforeWritingFile(result);

            CompressJpeg(originalFile, originalFile);

            OnCompleted(result);
        }
        protected override void ReadResponse(string response, string fileName)
        {
            if (response.Contains("\"savings_percent\":0}"))
            {
                OnCompleted(new CrunchResult(fileName, this.Service));
                return;
            }

            JavaScriptSerializer jSerialize = new JavaScriptSerializer();
            PunyPngResponse      sir        = jSerialize.Deserialize <PunyPngResponse>(response);

            Uri url;

            if (!Uri.TryCreate(sir.optimized_url, UriKind.Absolute, out url))
            {
                OnCompleted(new CrunchResult(fileName, this.Service));
                return;
            }

            var result = new CrunchResult(fileName, this.Service)
            {
                SizeBefore   = sir.original_size,
                SizeAfter    = sir.optimized_size,
                PercentSaved = sir.savings_percent
            };

            if (result.SizeAfter != result.SizeBefore)
            {
                OnBeforeWritingFile(result);
                using (WebClient client = new WebClient())
                {
                    client.DownloadFile(url, fileName);
                }
            }

            OnCompleted(result);
        }
예제 #5
0
 public CruncherEventArgs(CrunchResult result)
 {
     this.Result = result;
 }