/// <summary>
 /// Runs the processor.
 /// 
 /// </summary>
 /// <param name="args">The arguments.</param>
 public void Process(GetMediaStreamPipelineArgs args)
 {
     Assert.ArgumentNotNull((object)args, "args");
     MediaStream outputStream = args.OutputStream;
     if (outputStream == null || args.Options.Thumbnail)
         return;
     if (!outputStream.AllowMemoryLoading)
     {
         Tracer.Error((object)"Could not crop image as it was larger than the maximum size allowed for memory processing. Media item: {0}", (object)outputStream.MediaItem.Path);
     }
     else
     {
         if (!args.MediaData.MimeType.StartsWith("image/", StringComparison.Ordinal))
             return;
         string extension = args.MediaData.Extension;
         ImageFormat imageFormat = MediaManager.Config.GetImageFormat(extension, (ImageFormat)null);
         if (imageFormat == null)
             return;
         CustomTransformationOptions transformationOptions = new CustomMediaOptions(args.Options).GetTransformationOptions();
         if (!transformationOptions.ContainsCropping())
             return;
         this.ApplyBackgroundColor(args, imageFormat, transformationOptions);
         MediaStream mediaStream = outputStream;
         Stream stream = CustomMediaManager.Effects.TransformImageStream(mediaStream.Stream, transformationOptions, imageFormat);
         args.OutputStream = new MediaStream(stream, extension, mediaStream.MediaItem);
     }
 }
Example #2
0
        public void Process(GetMediaStreamPipelineArgs args)
        {
            Assert.ArgumentNotNull(args, "args");
            if (args.Options.Thumbnail || !IsJpegImageRequest(args.MediaData.MimeType))
            {
                return;
            }
            if (args.OutputStream == null || !args.OutputStream.AllowMemoryLoading)
            {
                return;
            }
            var jpegQualityQuery = WebUtil.GetQueryString(JpegCompressionLevelQueryKey);

            if (string.IsNullOrEmpty(jpegQualityQuery))
            {
                return;
            }
            int jpegQuality;

            if (!int.TryParse(jpegQualityQuery, out jpegQuality) || jpegQuality <= 0 || jpegQuality > 100)
            {
                return;
            }
            var compressedStream = ChangeJpegCompressionLevelService.Change(args.OutputStream, jpegQuality);

            args.OutputStream = new MediaStream(compressedStream, args.MediaData.Extension, args.OutputStream.MediaItem);
        }
Example #3
0
 private bool ShouldProcess(GetMediaStreamPipelineArgs args)
 {
     return (args.Options.Thumbnail
                 && args.MediaData.MediaItem.FileBased
                 && !string.IsNullOrEmpty(args.MediaData.MediaItem.Icon)
                 && args.MediaData.MediaItem.Icon.StartsWith(SC.Settings.Media.MediaLinkPrefix));
 }
Example #4
0
        /// <summary>
        /// Builds the outputstream (new Image) with the propriate format from the selection (png, jpg, gif);
        /// </summary>
        /// <param name="pArgs">TheMediaStreamPipline argument</param>
        /// <param name="pBitmap">The manipulated bitmap</param>
        private void CreateMediaStream(GetMediaStreamPipelineArgs pArgs, Bitmap pBitmap)
        {
            if (pArgs.OutputStream != null && pArgs.OutputStream.Stream != null)
            {
                var stream = new MemoryStream();
                var format = pArgs.OutputStream.Extension;
                var flag   = false;

                switch (format)
                {
                case "jpg":
                    pBitmap.Save(stream, ImageFormat.Jpeg);
                    break;

                case "png":
                    pBitmap.Save(stream, ImageFormat.Png);
                    break;

                case "gif":
                    pBitmap.Save(stream, ImageFormat.Gif);
                    break;

                default:
                    pBitmap.Save(stream, ImageFormat.Jpeg);
                    flag = true;
                    break;
                }

                pArgs.OutputStream = flag ? new MediaStream(stream, "jpg", pArgs.MediaData.MediaItem) : new MediaStream(stream, pArgs.OutputStream.Extension, pArgs.MediaData.MediaItem);
            }
        }
 private bool ShouldProcess(GetMediaStreamPipelineArgs args)
 {
     return(args.Options.Thumbnail &&
            args.MediaData.MediaItem.FileBased &&
            !string.IsNullOrEmpty(args.MediaData.MediaItem.Icon) &&
            args.MediaData.MediaItem.Icon.StartsWith(SC.Settings.Media.MediaLinkPrefix));
 }
 /// <summary>
 /// Applies the color of the background.
 /// 
 /// </summary>
 /// <param name="args">The arguments.</param><param name="imageFormat">The image format.</param><param name="transformationOptions">The transformation options.</param>
 protected virtual void ApplyBackgroundColor(GetMediaStreamPipelineArgs args, ImageFormat imageFormat, CustomTransformationOptions transformationOptions)
 {
     Assert.ArgumentNotNull((object)args, "args");
     Assert.ArgumentNotNull((object)imageFormat, "imageFormat");
     Assert.ArgumentNotNull((object)transformationOptions, "transformationOptions");
     if (!transformationOptions.BackgroundColor.IsEmpty || imageFormat != ImageFormat.Bmp && imageFormat != ImageFormat.Gif && imageFormat != ImageFormat.Jpeg)
         return;
     transformationOptions.BackgroundColor = Settings.Media.DefaultImageBackgroundColor;
 }
Example #7
0
 /// <summary>
 /// Applies the color of the background.
 ///
 /// </summary>
 /// <param name="args">The arguments.</param><param name="imageFormat">The image format.</param><param name="transformationOptions">The transformation options.</param>
 protected virtual void ApplyBackgroundColor(GetMediaStreamPipelineArgs args, ImageFormat imageFormat, CustomTransformationOptions transformationOptions)
 {
     Assert.ArgumentNotNull((object)args, "args");
     Assert.ArgumentNotNull((object)imageFormat, "imageFormat");
     Assert.ArgumentNotNull((object)transformationOptions, "transformationOptions");
     if (!transformationOptions.BackgroundColor.IsEmpty || imageFormat != ImageFormat.Bmp && imageFormat != ImageFormat.Gif && imageFormat != ImageFormat.Jpeg)
     {
         return;
     }
     transformationOptions.BackgroundColor = Settings.Media.DefaultImageBackgroundColor;
 }
Example #8
0
        public void Process(GetMediaStreamPipelineArgs args)
        {
            Sitecore.Diagnostics.Assert.ArgumentNotNull((object)args, "args");
            if (args.Options.Thumbnail)
            {
                return;
            }
            MediaStream outputStream = args.OutputStream;

            if (outputStream == null)
            {
                return;
            }
            if (!outputStream.AllowMemoryLoading)
            {
                Tracer.Error((object)"Could not resize image as it was larger than the maximum size allowed for memory processing. Media item: {0}", (object)outputStream.MediaItem.Path);
            }
            else
            {
                if (!args.MediaData.MimeType.StartsWith("image/", StringComparison.Ordinal))
                {
                    return;
                }
                string          str            = args.MediaData.Extension.ToLower();
                IImageOptimizer imageOptimizer = (IImageOptimizer)null;
                if (str.Equals("png"))
                {
                    imageOptimizer = (IImageOptimizer) new PngOptimizer(outputStream.Stream);
                }
                if (str.Equals("jpg") || str.Equals("jpeg"))
                {
                    imageOptimizer = (IImageOptimizer) new JpegOptimizer(outputStream.Stream);
                }
                if (imageOptimizer == null)
                {
                    return;
                }
                Stopwatch stopwatch = new Stopwatch();
                stopwatch.Start();
                IOptimizerResult optimizerResult = imageOptimizer.Optimize();
                stopwatch.Stop();
                if (optimizerResult.Success)
                {
                    outputStream.Stream.Close();
                    Sitecore.Diagnostics.Log.Info(StringExtensions.FormatWith("HealthIS: optimized {0}.{1} ({2} bytes) - saved {3} bytes / {4:p}. Optimized in {5}ms.", (object)args.OutputStream.MediaItem.MediaPath, (object)args.OutputStream.MediaItem.Extension, (object)optimizerResult.SizeAfter, (object)(optimizerResult.SizeBefore - optimizerResult.SizeAfter), (object)(float)(1.0 - (double)optimizerResult.SizeAfter / (double)optimizerResult.SizeBefore), (object)stopwatch.ElapsedMilliseconds), (object)this);
                    args.OutputStream = new MediaStream(optimizerResult.CreateResultStream(), outputStream.Extension, outputStream.MediaItem);
                }
                else
                {
                    Sitecore.Diagnostics.Log.Error(StringExtensions.FormatWith("HealthIS: unable to optimize {0} because {1}", (object)args.OutputStream.MediaItem.Name, (object)optimizerResult.ErrorMessage), (object)this);
                }
            }
        }
        public void Process(GetMediaStreamPipelineArgs args)
        {
            if (args.MediaData.Extension.Equals("PNG"))
            {
                var builder = new UrlBuilder("bensterrett.imgix.net")
                {
                    SignKey = WebConfigurationManager.AppSettings["imgixSecret"]
                };

                HttpContext.Current.Response.Redirect(builder.BuildUrl(HttpUtility.UrlEncode(args.MediaData.MediaItem.ID.ToString())));

                args.AbortPipeline();
            }
        }
Example #10
0
        public void Process(GetMediaStreamPipelineArgs args)
        {
            if (args.MediaData.Extension.Equals("PNG"))
            {
                var builder = new UrlBuilder("bensterrett.imgix.net")
                {
                    SignKey = WebConfigurationManager.AppSettings["imgixSecret"]
                };

                HttpContext.Current.Response.Redirect(builder.BuildUrl(HttpUtility.UrlEncode(args.MediaData.MediaItem.ID.ToString())));

                args.AbortPipeline();
            }
        }
Example #11
0
        public void Process(GetMediaStreamPipelineArgs args)
        {
            if (!ShouldProcess(args))
                return;

            var helper = new MediaHelper(args.MediaData.MediaItem);
            MediaStream thumbnailStream = helper.GetThumbnailStream();

            if (thumbnailStream != null)
            {
                args.OutputStream = thumbnailStream;
                args.AbortPipeline();
            }
        }
Example #12
0
        public void Process(GetMediaStreamPipelineArgs args)
        {
            Assert.ArgumentNotNull(args, "args");

            if (args.MediaData.MimeType.Equals("image/svg+xml", StringComparison.Ordinal))
            {
                // if the synchronous flag is set, the SVG will be optimized before we abort the pipeline to prevent
                // Sitecore from trying to process an SVG. Set this flag when NOT using the media cache async optimization strategy.
                if (SynchronouslyOptimizeSvgs && !(MediaManager.Cache is OptimizingMediaCache))
                {
                    new OptimizeImage().Process(args);
                }

                args.AbortPipeline();
            }
        }
        public void Process(GetMediaStreamPipelineArgs args)
        {
            if (!ShouldProcess(args))
            {
                return;
            }

            var         helper          = new MediaHelper(args.MediaData.MediaItem);
            MediaStream thumbnailStream = helper.GetThumbnailStream();

            if (thumbnailStream != null)
            {
                args.OutputStream = thumbnailStream;
                args.AbortPipeline();
            }
        }
Example #14
0
        public void Process(GetMediaStreamPipelineArgs args)
        {
            Assert.ArgumentNotNull(args, "args");

            if (args.Options.Thumbnail)
            {
                return;
            }
            if (Sitecore.Context.Site?.Name == "shell")
            {
                return;
            }

            MediaStream outputStream = args.OutputStream;

            if (outputStream == null)
            {
                return;
            }

            if (!outputStream.AllowMemoryLoading)
            {
                Tracer.Error("Could not resize image as it was larger than the maximum size allowed for memory processing. Media item: {0}", outputStream.MediaItem.Path);
                return;
            }

            MediaStream optimizedOutputStream = _optimizer.Process(outputStream, args.Options);

            if (optimizedOutputStream != null && outputStream.Stream != optimizedOutputStream.Stream)
            {
                outputStream.Dispose();                 // Uses thread safe dispose helper that won't double dispose

                args.OutputStream = optimizedOutputStream;

                if (optimizedOutputStream.Extension == "webp")
                {
                    // WebP processor has handled everything including resizing
                    args.AbortPipeline();
                }
            }
            else
            {
                var mediaPath = outputStream.MediaItem.MediaPath;
                Log.Info($"Dianoga: {mediaPath} cannot be optimized due to media type or path exclusion", this);
            }
        }
Example #15
0
        protected static void GetWebsiteScripts(GetMediaStreamPipelineArgs args, ID targetItemId)
        {
            string targetItemUrl;
            string site = string.IsNullOrEmpty(args.Options.CustomOptions["site"])
                              ? "website"
                              : args.Options.CustomOptions["site"];

            using (new SiteContextSwitcher(SiteContext.GetSite(site)))
            {
                var item = Sitecore.Context.Database.GetItem(targetItemId);
                if (item == null)
                {
                    return;
                }

                var options = new UrlOptions();
                options.LanguageEmbedding      = LanguageEmbedding.Never;
                options.AlwaysIncludeServerUrl = true;
                targetItemUrl = LinkManager.GetItemUrl(item, options);
            }

            var    fileName   = string.Format("SplitShot_{0}.png", ID.NewID);
            string tempPath   = HttpContext.Current.Server.MapPath("/temp");
            string serverPath = HttpContext.Current.Server.MapPath("/App_Data/SplitShot");
            string arguments  = string.Format(" rasterize.js \"{0}\" {1}\\{2}", targetItemUrl, tempPath, fileName);
            var    psi        = new System.Diagnostics.ProcessStartInfo(string.Format("{0}\\phantomjs.exe", serverPath), arguments)
            {
                UseShellExecute        = false,
                RedirectStandardOutput = true,
                RedirectStandardInput  = true,
                RedirectStandardError  = true,
                WorkingDirectory       = serverPath
            };

            var process = System.Diagnostics.Process.Start(psi);

            process.WaitForExit();

            var stream = new MemoryStream();

            AddFileToStream(stream, "/temp/" + fileName);

            args.OutputStream = new MediaStream(stream, "png", args.MediaData.MediaItem);
        }
        public static void Process(GetMediaStreamPipelineArgs args)
        {
            bool enabled = Settings.GetBoolSetting("Sitecore.SharedSource.SplitShot.Enabled", false);
            if(!enabled)
            {
                return;
            }

            var itemId = args.Options.CustomOptions["itemId"];
            if (itemId != null)
            {
                ID targetItemId;
                if (!ID.TryParse(args.Options.CustomOptions["itemId"], out targetItemId))
                {
                    return;
                }

                GetWebsiteScripts(args, targetItemId);
            }
        }
        protected static void GetWebsiteScripts(GetMediaStreamPipelineArgs args, ID targetItemId)
        {
            string targetItemUrl;
            string site = string.IsNullOrEmpty(args.Options.CustomOptions["site"])
                              ? "website"
                              : args.Options.CustomOptions["site"];
            using (new SiteContextSwitcher(SiteContext.GetSite(site)))
            {
                var item = Sitecore.Context.Database.GetItem(targetItemId);
                if (item == null)
                {
                    return;
                }

                var options = new UrlOptions();
                options.LanguageEmbedding = LanguageEmbedding.Never;
                options.AlwaysIncludeServerUrl = true;
                targetItemUrl = LinkManager.GetItemUrl(item, options);
            }

            var fileName = string.Format("SplitShot_{0}.png", ID.NewID);
            string tempPath = HttpContext.Current.Server.MapPath("/temp");
            string serverPath = HttpContext.Current.Server.MapPath("/App_Data/SplitShot");
            string arguments = string.Format(" rasterize.js \"{0}\" {1}\\{2}", targetItemUrl, tempPath, fileName);
            var psi = new System.Diagnostics.ProcessStartInfo(string.Format("{0}\\phantomjs.exe", serverPath), arguments)
                          {
                              UseShellExecute = false,
                              RedirectStandardOutput = true,
                              RedirectStandardInput = true,
                              RedirectStandardError = true,
                              WorkingDirectory = serverPath
                          };

            var process = System.Diagnostics.Process.Start(psi);
            process.WaitForExit();

            var stream = new MemoryStream();
            AddFileToStream(stream, "/temp/" + fileName);

            args.OutputStream = new MediaStream(stream, "png", args.MediaData.MediaItem);
        }
        public void Process(GetMediaStreamPipelineArgs args)
        {
            Assert.ArgumentNotNull(args, "args");

            var outputStream = args.OutputStream;

            if (outputStream == null)
            {
                return;
            }

            if (!IMAGE_EXTENSIONS.Any(i => i.Equals(args.MediaData.Extension, StringComparison.InvariantCultureIgnoreCase)))
            {
                return;
            }

            var   cx = args.Options.CustomOptions["cx"];
            var   cy = args.Options.CustomOptions["cy"];
            var   width = args.Options.CustomOptions["cw"];
            var   height = args.Options.CustomOptions["ch"];
            float x, y;
            int   w, h;

            if (!string.IsNullOrEmpty(cx) && !string.IsNullOrEmpty(cy) && float.TryParse(cx, out x) && float.TryParse(cy, out y) &&
                !string.IsNullOrEmpty(width) && Int32.TryParse(width, out w) && !string.IsNullOrEmpty(height) && Int32.TryParse(height, out h))
            {
                var outputStrm = Stream.Synchronized(GetCroppedImage(args.MediaData.Extension, w, h, x, y, outputStream.MediaItem));
                args.OutputStream = new MediaStream(outputStrm, args.MediaData.Extension, outputStream.MediaItem);
            }
            else if (args.Options.Thumbnail)
            {
                TransformationOptions transformationOptions = args.Options.GetTransformationOptions();
                MediaStream           thumbnailStream       = args.MediaData.GetThumbnailStream(transformationOptions);

                if (thumbnailStream != null)
                {
                    args.OutputStream = thumbnailStream;
                }
            }
        }
Example #19
0
        public static void Process(GetMediaStreamPipelineArgs args)
        {
            bool enabled = Settings.GetBoolSetting("Sitecore.SharedSource.SplitShot.Enabled", false);

            if (!enabled)
            {
                return;
            }

            var itemId = args.Options.CustomOptions["itemId"];

            if (itemId != null)
            {
                ID targetItemId;
                if (!ID.TryParse(args.Options.CustomOptions["itemId"], out targetItemId))
                {
                    return;
                }

                GetWebsiteScripts(args, targetItemId);
            }
        }
        protected bool ShouldSkip(GetMediaStreamPipelineArgs args)
        {
            MediaData mediaData = args.MediaData;

            if (!mediaData.MimeType.StartsWith("image/", StringComparison.Ordinal))
            {
                return(true);
            }
            if (mediaData.MimeType.StartsWith("image/webp", StringComparison.Ordinal))
            {
                return(true);
            }
            if (!args.Options.CustomOptions.ContainsKey("webp") || args.Options.CustomOptions["webp"] != "1")
            {
                return(true);
            }
            if (!args.MediaData.HasContent)
            {
                return(true);
            }
            return(false);
        }
 public void Process(GetMediaStreamPipelineArgs args)
 {
     Sitecore.Diagnostics.Log.Debug("::WEBP:: enabled:" + (args.Options.CustomOptions.ContainsKey("webp") || args.Options.CustomOptions["webp"] == "1").ToString(), this);
     Assert.ArgumentNotNull(args, "args");
     if (!ShouldSkip(args))
     {
         Sitecore.Diagnostics.Log.Debug("::WEBP:: converting " + args.MediaData.MediaItem.InnerItem.Paths.Path, this);
         ISupportedImageFormat format = new WebPFormat()
         {
             Quality = Sitecore.Configuration.Settings.GetIntSetting("Media.Resizing.Quality", 70)
         };
         MemoryStream outstream = new MemoryStream();
         using (Stream stream = args.MediaData.MediaItem.GetMediaStream())
         {
             using (ImageFactory imageFactory = new ImageFactory(preserveExifData: true))
             {
                 imageFactory.Load(stream).Format(format).Save(outstream);
                 args.OutputStream = new MediaStream(outstream, "webp", args.MediaData.MediaItem);
                 args.OutputStream.Headers.Headers["Content-Type"] = "image/webp";
             }
         }
     }
 }
Example #22
0
        /// <summary>
        /// Runs the processor.
        ///
        /// </summary>
        /// <param name="args">The arguments.</param>
        public void Process(GetMediaStreamPipelineArgs args)
        {
            Assert.ArgumentNotNull((object)args, "args");
            MediaStream outputStream = args.OutputStream;

            if (outputStream == null || args.Options.Thumbnail)
            {
                return;
            }
            if (!outputStream.AllowMemoryLoading)
            {
                Tracer.Error((object)"Could not crop image as it was larger than the maximum size allowed for memory processing. Media item: {0}", (object)outputStream.MediaItem.Path);
            }
            else
            {
                if (!args.MediaData.MimeType.StartsWith("image/", StringComparison.Ordinal))
                {
                    return;
                }
                string      extension   = args.MediaData.Extension;
                ImageFormat imageFormat = MediaManager.Config.GetImageFormat(extension, (ImageFormat)null);
                if (imageFormat == null)
                {
                    return;
                }
                CustomTransformationOptions transformationOptions = new CustomMediaOptions(args.Options).GetTransformationOptions();
                if (!transformationOptions.ContainsCropping())
                {
                    return;
                }
                this.ApplyBackgroundColor(args, imageFormat, transformationOptions);
                MediaStream mediaStream = outputStream;
                Stream      stream      = CustomMediaManager.Effects.TransformImageStream(mediaStream.Stream, transformationOptions, imageFormat);
                args.OutputStream = new MediaStream(stream, extension, mediaStream.MediaItem);
            }
        }
Example #23
0
        public void Process(GetMediaStreamPipelineArgs args)
        {
            try
            {
                if (!args.Options.Thumbnail)
                {
                    return;
                }

                TransformationOptions transformationOptions = args.Options.GetTransformationOptions();
                ImageFormat           imageFormat           = MediaManager.Config.GetImageFormat(args.MediaData.MediaItem.Extension);

                var imageResizer = new ImageResizer();
                var stream       = imageResizer.ResizeImageFromStream(args.MediaData.GetStream().Stream, transformationOptions, imageFormat);
                if (stream != null)
                {
                    args.OutputStream = new MediaStream(stream, args.MediaData.MediaItem.Extension, args.MediaData.MediaItem);
                }
            }
            catch (Exception ex)
            {
                Log.Error($"Error while generating thumbnail for media item: {args.MediaData.MediaId}", ex, this);
            }
        }
Example #24
0
        /// <summary>
        /// Called by Sitecore getMediaStream processor
        /// </summary>
        /// <param name="pArgs">Args from Sitecore getMediaStream pipeline containing image to process</param>
        public void Process(GetMediaStreamPipelineArgs pArgs)
        {
            // variable value should be "1" to activate namics image manipulation functionality
            var useCustomFunctionsArg = pArgs.Options.CustomOptions["useCustomFunctions"];

            if (string.IsNullOrEmpty(useCustomFunctionsArg))
            {
                return;
            }

            if (!useCustomFunctionsArg.Equals("1"))
            {
                return;
            }

            try
            {
                var bm = (Bitmap)Image.FromStream(pArgs.OutputStream.Stream);

                int startXArg, startYArg;
                var isStartXParsable = int.TryParse(pArgs.Options.CustomOptions["cropX"], out startXArg);
                var isStartYParsable = int.TryParse(pArgs.Options.CustomOptions["cropY"], out startYArg);

                // keepOrientatioln parameter from url
                var keepOrientationArg = pArgs.Options.CustomOptions["keepOrientation"];
                if (!string.IsNullOrEmpty(keepOrientationArg))
                {
                    if (keepOrientationArg.Equals("1"))
                    {
                        foreach (var orientation in from prop in bm.PropertyItems where prop.Id == 0x0112 select prop.Value[0])
                        {
                            string processString;

                            switch (orientation)
                            {
                            case 1:
                                processString = "RotateNoneFlipNone";
                                break;

                            case 2:
                                processString = "RotateNoneFlipX";
                                break;

                            case 3:
                                processString = "Rotate180FlipNone";
                                break;

                            case 4:
                                processString = "Rotate180FlipX";
                                break;

                            case 5:
                                processString = "Rotate90FlipX";
                                break;

                            case 6:
                                processString = "Rotate90FlipNone";
                                break;

                            case 7:
                                processString = "Rotate270FlipX";
                                break;

                            case 8:
                                processString = "Rotate270FlipNone";
                                break;

                            default:
                                processString = "RotateNoneFlipNone";
                                break;
                            }

                            if (!string.IsNullOrEmpty(processString))
                            {
                                bm = ProcessRotateFlip(bm, processString);
                            }
                        }
                    }
                }

                // Process pixel accurate cropping whenn all boolparameters are true
                if (isStartXParsable && isStartYParsable && pArgs.Options.Height > 0 && pArgs.Options.Width > 0)
                {
                    bm = ProcessCropping(bm, startXArg, startYArg, pArgs.Options.Width, pArgs.Options.Height);
                }

                // only crop image if we have a custom width and height (and crop=1)
                var crop = pArgs.Options.CustomOptions["centerCrop"];
                if (crop != null)
                {
                    var originalProportion = ((double)bm.Width) / bm.Height;
                    var argumentProportion = ((double)pArgs.Options.Width) / pArgs.Options.Height;

                    if (!originalProportion.Equals(argumentProportion))
                    {
                        if (crop.Equals("1") && pArgs.Options.Height > 0 && pArgs.Options.Width > 0)
                        {
                            bm = ProcessCenterCropping(pArgs.Options.Width, pArgs.Options.Height, bm);
                        }
                    }
                }

                // greyScale parameter from url
                var greyScaleArg = pArgs.Options.CustomOptions["greyScale"];
                if (!string.IsNullOrEmpty(greyScaleArg))
                {
                    if (greyScaleArg.Equals("1"))
                    {
                        bm = ProcessGreyScale(bm);
                    }
                }

                // rotate flip parameter from url
                var rotateFlip = pArgs.Options.CustomOptions["rotateFlip"];

                if (!string.IsNullOrEmpty(rotateFlip))
                {
                    bm = ProcessRotateFlip(bm, rotateFlip);
                }

                /**********************************************
                *  Add more image processing options here..
                **********************************************/

                // Write manipulatet bitmap back to the Stream
                CreateMediaStream(pArgs, bm);
            }
            catch (Exception e)
            {
                Log.Error("Error while formatting image" + e.Message, typeof(ImageProcessor));
            }
        }
Example #25
0
        public void Process(GetMediaStreamPipelineArgs args)
        {
            Assert.ArgumentNotNull(args, "args");

            if (args.Options.Thumbnail)
            {
                return;
            }

            MediaStream outputStream = args.OutputStream;

            if (outputStream == null)
            {
                return;
            }

            if (!outputStream.AllowMemoryLoading)
            {
                Tracer.Error("Could not resize image as it was larger than the maximum size allowed for memory processing. Media item: {0}", outputStream.MediaItem.Path);
                return;
            }

            string mimeType = args.MediaData.MimeType;

            if (!mimeType.StartsWith("image/", StringComparison.Ordinal))
            {
                return;
            }

            string extension = args.MediaData.Extension;

            IImageOptimizer optimizer = null;

            if (extension.Equals("png"))
            {
                optimizer = new PngOptimizer(outputStream.Stream);
            }

            if (extension.Equals("jpg") || extension.Equals("jpeg"))
            {
                optimizer = new JpegOptimizer(outputStream.Stream);
            }

            if (optimizer == null)
            {
                return;
            }

            var sw = new Stopwatch();

            sw.Start();

            var result = optimizer.Optimize();

            sw.Stop();

            if (result.Success)
            {
                outputStream.Stream.Close();

                Log.Info("Dianoga: optimized {0}.{1} ({2} bytes) - saved {3} bytes / {4:p}. Optimized in {5}ms.".FormatWith(args.OutputStream.MediaItem.MediaPath, args.OutputStream.MediaItem.Extension, result.SizeAfter, result.SizeBefore - result.SizeAfter, 1 - ((result.SizeAfter / (float)result.SizeBefore)), sw.ElapsedMilliseconds), this);

                args.OutputStream = new MediaStream(result.CreateResultStream(), outputStream.Extension, outputStream.MediaItem);
            }
            else
            {
                Log.Error("Dianoga: unable to optimize {0} because {1}".FormatWith(args.OutputStream.MediaItem.Name, result.ErrorMessage), this);
            }
        }
        public void Process(GetMediaStreamPipelineArgs args)
        {
            Assert.ArgumentNotNull(args, "args");
            if (args.Options.Thumbnail || !IsValidImageRequest(args.MediaData.MimeType))
            {
                return;
            }
            if (args.OutputStream == null || !args.OutputStream.AllowMemoryLoading)
            {
                return;
            }
            var cropKey = GetQueryOrCustomOption(CropQueryKey, args.Options.CustomOptions);

            if (string.IsNullOrEmpty(cropKey))
            {
                return;
            }
            var cropWidthOption  = GetQueryOrCustomOption(CropWidthQueryKey, args.Options.CustomOptions);
            var cropHeightOption = GetQueryOrCustomOption(CropHeightQueryKey, args.Options.CustomOptions);

            if (string.IsNullOrEmpty(cropWidthOption) && string.IsNullOrEmpty(cropHeightOption))
            {
                return;
            }
            int cropWidth;

            if (!int.TryParse(cropWidthOption, out cropWidth))
            {
                cropWidth = args.Options.Width;
            }
            int cropHeight;

            if (!int.TryParse(cropHeightOption, out cropHeight))
            {
                cropHeight = args.Options.Height;
            }

            var cha = GetQueryOrCustomOption(CropHorizontalAlignmentKey, args.Options.CustomOptions);

            var cropHorizontalAlignment = HorizontalAlignment.Center;

            if (string.IsNullOrEmpty(cha))
            {
                cropHorizontalAlignment = HorizontalAlignment.Center;
            }
            else
            {
                cropHorizontalAlignment = (HorizontalAlignment)Enum.Parse(typeof(HorizontalAlignment), cha, true);
            }

            var cva = GetQueryOrCustomOption(CropVerticalAlignmentKey, args.Options.CustomOptions);

            var cropVerticalAlignment = VerticalAlignment.Middle;

            if (string.IsNullOrEmpty(cva))
            {
                cropVerticalAlignment = VerticalAlignment.Middle;
            }
            else
            {
                cropVerticalAlignment = (VerticalAlignment)Enum.Parse(typeof(VerticalAlignment), cva, true);
            }

            var croppedStream = CropImageService.CenterCrop(
                args.OutputStream.Stream,
                cropWidth,
                cropHeight,
                GetImageFormat(args.MediaData.MimeType.ToLower()),
                cropHorizontalAlignment,
                cropVerticalAlignment);

            args.OutputStream = new MediaStream(croppedStream, args.MediaData.Extension, args.OutputStream.MediaItem);
        }