public void Process(AttachArgs args)
        {
            MediaItem mi = args.MediaItem;

            try
            {
                CrunchOptions crunchOptions;
                if (mi != null)
                {
                    crunchOptions = new CrunchOptions();
                    FillSetting   objFillSetting    = new FillSetting();
                    TenantSetting objTennantSetting = objFillSetting.getSetting(mi.MediaPath, mi.Database.Name, mi.InnerItem.Language.ToString());
                    if (mi.Size > objTennantSetting.MinimumKBSize && mi.Size < objTennantSetting.MaxImageSize)
                    {
                        crunchOptions.APIKey    = objTennantSetting.ApiKey;
                        crunchOptions.APISecret = objTennantSetting.ApiSecret;
                        crunchOptions.fullname  = mi.Name + "." + mi.Extension;
                        crunchOptions.IsEnabled = objTennantSetting.IsEnabled;
                        crunchOptions.wait      = true;
                        crunchOptions.lossy     = objTennantSetting.Lossy;
                        crunchOptions.dev       = objTennantSetting.IsDev;
                        crunchOptions.enhance   = objTennantSetting.Enhance;
                        CrunchImage.ProcessMediaItem(mi, crunchOptions);
                    }
                    else
                    {
                        Log.Info(string.Format("Image Size is {0} {1}", mi.Size, ",KB which is not fit in minimum & maximum size defined in setting"), this);
                    }
                }
            }
            catch (System.Exception exception)
            {
                Log.Error(string.Format("Could not shrink item {0}", mi.InnerItem.Paths.FullPath), exception, this);
            }
        }
Пример #2
0
        protected virtual void Shrink(object[] parameters)
        {
            Item item = parameters[0] as Item;

            if (item == null)
            {
                throw new Exception("Parameter 0 was not a item");
            }
            else
            {
                mi                = new MediaItem(item);
                crunchOptions     = new CrunchOptions();
                objFillSetting    = new FillSetting();
                objTennantSetting = objFillSetting.getSetting(mi.MediaPath, mi.Database.Name, mi.InnerItem.Language.ToString());
                if (mi.Size > objTennantSetting.MinimumKBSize && mi.Size < objTennantSetting.MaxImageSize)
                {
                    crunchOptions.APIKey    = objTennantSetting.ApiKey;
                    crunchOptions.APISecret = objTennantSetting.ApiSecret;
                    crunchOptions.fullname  = mi.Name + "." + mi.Extension;
                    crunchOptions.IsEnabled = objTennantSetting.IsEnabled;
                    crunchOptions.wait      = true;
                    crunchOptions.lossy     = objTennantSetting.Lossy;
                    crunchOptions.dev       = objTennantSetting.IsDev;
                    crunchOptions.enhance   = objTennantSetting.Enhance;
                    CrunchImage.ProcessMediaItem(mi, crunchOptions);
                }
                else
                {
                    Log.Info(string.Format("Image Size is {0} {1}", mi.Size, ",KB which is not fit in minimum & maximum size defined in setting"), this);
                }
            }
        }
Пример #3
0
        public static long ProcessMediaItem(MediaItem mediaItem, CrunchOptions crunchOptions)
        {
            long resultantSize = 0;

            if (crunchOptions.IsEnabled)
            {
                if (mediaItem.MimeType == "image/jpeg" || mediaItem.MimeType == "image/pjpeg" ||
                    mediaItem.MimeType == "image/gif" || mediaItem.MimeType == "image/png")
                {
                    ICruncher cruncher = Cruncher.GetCruncher();
                    if (cruncher == null)
                    {
                        Log.Error("Could not find cruncher!", typeof(CrunchImage));
                        return(resultantSize);
                    }
                    if (mediaItem.Size >= cruncher.MaxImageSize)
                    {
                        return(resultantSize);
                    }
                    var mediaStream = mediaItem.GetMediaStream();
                    Job job         = Context.Job;
                    try
                    {
                        CrunchResult result = cruncher.CrunchStream(mediaStream, crunchOptions);

                        if (result == null)
                        {
                            Log.Error(string.Format("Could not shrink media file {0}", mediaItem.InnerItem.Paths.Path),
                                      typeof(CrunchImage));
                        }
                        Sitecore.Resources.Media.Media media = MediaManager.GetMedia(mediaItem);
                        using (var stream = new MemoryStream())
                        {
                            result.FileStream.CopyTo(stream);
                            stream.Position = 0;
                            resultantSize   = stream.Length;
                            media.SetStream(stream, Path.GetExtension(result.Format).TrimStart('.'));
                        }
                    }
                    catch (Exception exception)
                    {
                        if (job != null)
                        {
                            job.Status.LogError("Image could not be reduced in size");
                        }
                        Log.Error(string.Format("Image crunch failed: {0}", mediaItem.InnerItem.Paths.FullPath), exception,
                                  (typeof(CrunchImage)));
                    }
                }
            }
            return(resultantSize);
        }
Пример #4
0
        public void CreateRequest()
        {
            var assembly     = Assembly.GetExecutingAssembly();
            var resourceName = "InSitecore.ImageCrunch.SmushIt.Tests.TestResources.testPicture.jpg";

            using (Stream stream = assembly.GetManifestResourceStream(resourceName))
            {
                var memoryStream = new MemoryStream();
                stream.CopyTo(memoryStream);
                memoryStream.Position = 0;
                var           cruncher = new SmushItCruncher();
                CrunchOptions crunchOptions;
                crunchOptions = new CrunchOptions();
                CrunchResult request = cruncher.CrunchStream(memoryStream, crunchOptions);
            }
        }
        public CrunchResult CrunchStream(Stream stream, CrunchOptions cruncheroptions)
        {
            var client  = new HttpClient();
            var content = new MultipartFormDataContent();

            content.Add(new StreamContent(stream), "\"files\"", "empty");

            HttpResponseMessage postAsync = client.PostAsync("http://www.smushit.com/ysmush.it/ws.php", content).Result;

            SmushItResponse jsonResult = null;

            if (postAsync.IsSuccessStatusCode)
            {
                string stringResult = postAsync.Content.ReadAsStringAsync().Result;

                var dynamicResut = JsonValue.Parse(stringResult);

                if (!dynamicResut.ContainsKey("error"))
                {
                    jsonResult = postAsync.Content.ReadAsAsync <SmushItResponse>().Result;
                }
                else
                {
                    throw new Exception(string.Format("Error: {0}", dynamicResut.GetValue("error").ReadAs <string>()));
                }
            }
            else
            {
                return(null);
            }

            HttpResponseMessage httpResponseMessage = client.GetAsync(jsonResult.Dest, HttpCompletionOption.ResponseHeadersRead).Result;

            if (!httpResponseMessage.IsSuccessStatusCode)
            {
                return(null);
            }

            Stream result = httpResponseMessage.Content.ReadAsStreamAsync().Result;

            var smushItObject = new Entities.CrunchResult();

            smushItObject.FileStream = result;
            smushItObject.Format     = Path.GetExtension(jsonResult.Dest);

            return(smushItObject);
        }
 public void Process(UploadArgs args)
 {
     Assert.ArgumentNotNull((object)args, "args");
     if (args != null && args.UploadedItems != null && args.UploadedItems[0] != null)
     {
         CrunchOptions crunchOptions;
         FillSetting   objFillSetting    = new FillSetting();
         MediaItem     mi                = args.UploadedItems[0];
         TenantSetting objTennantSetting = objFillSetting.getSetting(mi.MediaPath, mi.Database.Name, mi.InnerItem.Language.ToString());
         crunchOptions           = new CrunchOptions();
         crunchOptions.APIKey    = objTennantSetting.ApiKey;
         crunchOptions.APISecret = objTennantSetting.ApiSecret;
         crunchOptions.IsEnabled = objTennantSetting.IsEnabled;
         crunchOptions.wait      = true;
         crunchOptions.lossy     = objTennantSetting.Lossy;
         crunchOptions.dev       = objTennantSetting.IsDev;
         crunchOptions.enhance   = objTennantSetting.Enhance;
         foreach (Item uploadedItem in args.UploadedItems)
         {
             try
             {
                 mi = new MediaItem(uploadedItem);
                 //checking maximum & minimum size condition defined for the tenant
                 if (mi != null && mi.Size > objTennantSetting.MinimumKBSize && mi.Size < objTennantSetting.MaxImageSize)
                 {
                     crunchOptions.fullname = mi.Name + "." + mi.Extension;
                     //As of now API is based out of post approach
                     CrunchImage.ProcessMediaItem(mi, crunchOptions);
                 }
                 else
                 {
                     Log.Info(string.Format("Image Size is {0} {1}", mi.Size, ",KB which is not fit in minimum & maximum size defined in setting"), this);
                 }
             }
             catch (System.Exception exception)
             {
                 Log.Error(string.Format("Could not shrink item {0}", uploadedItem.Paths.FullPath), exception, this);
             }
         }
     }
 }
Пример #7
0
        protected override void Shrink(object[] parameters)
        {
            Item item = parameters[0] as Item;
            Job  job  = Context.Job;

            if (crunchedStats == null)
            {
                crunchedStats                 = new CrunchedStats();
                crunchedStats.JobID           = job.Name;
                crunchedStats.typeofExecution = CrunchedStats.TypeofExecution.CrunchbyTreeRibbonCommand;
            }
            if (item == null)
            {
                return;
            }
            else if (InSitecoreSitecore.Common.Functions.IsMediaItem(item))
            {
                mi = new MediaItem(item);
                //This make sures that no need to get setting item recursively for each child.
                if (objFillSetting == null)
                {
                    crunchOptions             = new CrunchOptions();
                    objFillSetting            = new FillSetting();
                    objTennantSetting         = objFillSetting.getSetting(mi.MediaPath, mi.Database.Name, mi.InnerItem.Language.ToString());
                    crunchOptions.APIKey      = objTennantSetting.ApiKey;
                    crunchOptions.APISecret   = objTennantSetting.ApiSecret;
                    crunchOptions.wait        = true;
                    crunchOptions.IsEnabled   = objTennantSetting.IsEnabled;
                    crunchOptions.enhance     = objTennantSetting.Enhance;
                    crunchOptions.lossy       = objTennantSetting.Lossy;
                    crunchOptions.dev         = objTennantSetting.IsDev;
                    crunchOptions.enhance     = objTennantSetting.Enhance;
                    crunchedStats.Database    = mi.Database.Name;
                    crunchedStats.InitiatedBy = Sitecore.Context.GetUserName();
                    Log.Info(string.Format("Job Started {0} by {1} on Database {2}", crunchedStats.JobID, crunchedStats.InitiatedBy, crunchedStats.Database), this);
                }
                if (objFillSetting.isInitialised)
                {
                    crunchOptions.fullname = mi.Name + "." + mi.Extension;
                    if (mi.Size > objTennantSetting.MinimumKBSize && mi.Size < objTennantSetting.MaxImageSize)
                    {
                        try
                        {
                            crunchedStats.BeforeCrunchSize = mi.Size;
                            if (sw == null)
                            {
                                sw = new Stopwatch();
                            }
                            sw.Start();
                            crunchedStats.AfterCrunchSize = CrunchImage.ProcessMediaItem(mi, crunchOptions);
                            sw.Stop();
                            crunchedStats.TimeTaken = sw.ElapsedMilliseconds;
                            if (job != null)
                            {
                                job.Status.LogInfo(string.Format("Done: {0}", item.Paths.FullPath));
                                Log.Info(string.Format("Done: {0}", item.Paths.FullPath), this);

                                job.Status.LogInfo(string.Format("Stats - Before Crunch Size: {0}", crunchedStats.BeforeCrunchSize));
                                Log.Info(string.Format("Stats - Before Crunch Size: {0}", crunchedStats.BeforeCrunchSize), this);

                                job.Status.LogInfo(string.Format("Stats - After Crunch Size: {0}", crunchedStats.AfterCrunchSize));
                                Log.Info(string.Format("Stats - After Crunch Size: {0}", crunchedStats.AfterCrunchSize), this);
                            }
                        }
                        catch (Exception catche)
                        {
                            if (job != null)
                            {
                                job.Status.LogInfo(string.Format("{0}: {1}", catche.Message, item.Paths.FullPath));
                            }
                        }
                    }
                    else
                    {
                        Log.Info(string.Format("Image Size is {0} {1}", mi.Size, ",KB which is not fit in minimum & maximum size defined in setting"), this);
                    }
                }
            }
            foreach (var child in item.Children)
            {
                this.Shrink(new[] { child });
            }
        }
Пример #8
0
        private JsonResult DoUpload(string database, string destinationUrl)
        {
            if (string.IsNullOrEmpty(destinationUrl))
            {
                destinationUrl = "/sitecore/media library";
            }
            List <UploadedFileItem> uploadedFileItemList = new List <UploadedFileItem>();
            SitecoreViewModelResult result = new SitecoreViewModelResult();

            if (!ImageCrunchController.ValidateDestination(database, destinationUrl, result))
            {
                return((JsonResult)result);
            }
            objFillSetting = new FillSetting();
            crunchOptions  = new CrunchOptions();
            foreach (string file1 in (NameObjectCollectionBase)this.Request.Files)
            {
                HttpPostedFileBase file2 = this.Request.Files[file1];
                if (file2 != null)
                {
                    string withoutExtension = Path.GetFileNameWithoutExtension(file2.FileName);
                    if (!string.IsNullOrEmpty(this.Request.Form["name"]))
                    {
                        withoutExtension = this.Request.Form["name"];
                    }
                    string str   = ItemUtil.ProposeValidItemName(withoutExtension, "default");
                    string empty = string.Empty;
                    if (!string.IsNullOrEmpty(this.Request.Form["alternate"]))
                    {
                        empty = this.Request.Form["alternate"];
                    }
                    Database database1 = Context.ContentDatabase;
                    if (!string.IsNullOrEmpty(database))
                    {
                        database1 = Factory.GetDatabase(database);
                    }
                    if (database1 == null)
                    {
                        database1 = Context.ContentDatabase;
                    }
                    MediaCreatorOptions options1 = new MediaCreatorOptions()
                    {
                        AlternateText = empty,
                        Database      = database1,
                        FileBased     = Settings.Media.UploadAsFiles,
                        IncludeExtensionInItemName = Settings.Media.IncludeExtensionsInItemNames,
                        OverwriteExisting          = false,
                        Language    = LanguageManager.DefaultLanguage,
                        Versioned   = Settings.Media.UploadAsVersionableByDefault,
                        Destination = this.ParseDestinationUrl(destinationUrl) + str
                    };
                    if (!ImageCrunchController.ValidateFile(file2, result))
                    {
                        return((JsonResult)result);
                    }
                    Item fromStream = MediaManager.Creator.CreateFromStream(file2.InputStream, "/upload/" + file2.FileName, options1);
                    if (!string.IsNullOrEmpty(this.Request.Form["description"]))
                    {
                        fromStream.Editing.BeginEdit();
                        fromStream["Description"] = this.Request.Form["description"];
                        fromStream.Editing.EndEdit();
                    }
                    MediaItem mediaItem = new MediaItem(fromStream);
                    ///Code to Shrunk the Media Item begin
                    objTennantSetting       = objFillSetting.getSetting(mediaItem.MediaPath, mediaItem.Database.Name, mediaItem.InnerItem.Language.ToString());
                    crunchOptions.APIKey    = objTennantSetting.ApiKey;
                    crunchOptions.APISecret = objTennantSetting.ApiSecret;
                    crunchOptions.IsEnabled = objTennantSetting.IsEnabled;
                    crunchOptions.wait      = true;
                    crunchOptions.lossy     = objTennantSetting.Lossy;
                    crunchOptions.dev       = objTennantSetting.IsDev;
                    crunchOptions.enhance   = objTennantSetting.Enhance;
                    try
                    {
                        //checking maximum & minimum size condition defined for the tenant
                        if (mediaItem != null && mediaItem.Size > objTennantSetting.MinimumKBSize && mediaItem.Size < objTennantSetting.MaxImageSize)
                        {
                            crunchOptions.fullname = mediaItem.Name + "." + mediaItem.Extension;
                            //As of now API is based out of post approach
                            CrunchImage.ProcessMediaItem(mediaItem, crunchOptions);
                        }
                        else
                        {
                            Log.Info(string.Format("Image Size is {0} {1}", mediaItem.Size, ",KB which is not fit in minimum & maximum size defined in setting"), this);
                        }
                    }
                    catch (System.Exception exception)
                    {
                        Log.Error(string.Format("Could not shrink item {0}", mediaItem.InnerItem.Paths.FullPath), exception, this);
                    }
                    ///Code to shrunk media item end
                    MediaUrlOptions options2 = new MediaUrlOptions(130, 130, false)
                    {
                        Thumbnail       = true,
                        BackgroundColor = Color.Transparent,
                        Database        = mediaItem.Database
                    };
                    string mediaUrl = MediaManager.GetMediaUrl(mediaItem, options2);
                    uploadedFileItemList.Add(new UploadedFileItem(fromStream.Name, fromStream.ID.ToString(), fromStream.ID.ToShortID().ToString(), mediaUrl));
                }
            }
            ((dynamic)result.Result).uploadedFileItems = uploadedFileItemList;
            return((JsonResult)result);
        }
        public CrunchResult CrunchStream(Stream stream, CrunchOptions options)
        {
            var        client  = new HttpClient();
            var        content = new MultipartFormDataContent();
            JsonObject parent  = new JsonObject();
            JsonObject auth    = null;

            #region Authentication
            ///JSON Object creation
            auth = new JsonObject
            {
                {
                    "api_key", options.APIKey
                },
                {
                    "api_secret", options.APISecret
                }
            };
            parent.Add("auth", auth);
            #endregion

            #region Configuration
            if (options.wait)
            {
                parent.Add("wait", options.wait);
            }
            else
            {
                parent.Add("callback_url", options.callbackurl);
            }
            if (options.dev)
            {
                parent.Add("dev", options.dev);
            }
            #endregion

            #region CustomImageQuality
            if (options.lossy)
            {
                parent.Add("lossy", options.lossy);
                if (options.quality != 0)
                {
                    parent.Add("quality", options.quality);
                }
            }
            #endregion

            JsonObject imageConversion = null;
            #region ImageConversion
            if (options.ImageConversion)
            {
                imageConversion = new JsonObject();
                switch (options.Format)
                {
                case CrunchOptions.format.jpeg:
                    imageConversion.Add("format", "jpeg");
                    break;

                case CrunchOptions.format.png:
                    imageConversion.Add("format", "png");
                    break;

                case CrunchOptions.format.gif:
                    imageConversion.Add("format", "gif");
                    break;

                default:
                    break;
                }
                if (options.background != null && options.background.Length > 0)
                {
                    imageConversion.Add("background", options.background);
                }
                if (options.keep_extension)
                {
                    imageConversion.Add("keep_extension", options.keep_extension);
                }
            }
            #endregion

            JsonObject resizevalues = null;
            #region ImageResizing
            if (options.ImageResizing)
            {
                resizevalues = new JsonObject();
                if (options.height != 0)
                {
                    resizevalues.Add("height", options.height);
                }
                if (options.width != 0)
                {
                    resizevalues.Add("width", options.width);
                }
                switch (options.Strategy)
                {
                case CrunchOptions.strategy.portrait:
                    resizevalues.Add("strategy", "portrait");
                    break;

                case CrunchOptions.strategy.landscape:
                    resizevalues.Add("strategy", "landscape");
                    break;

                case CrunchOptions.strategy.auto:
                    resizevalues.Add("strategy", "auto");
                    break;

                case CrunchOptions.strategy.crop:
                    resizevalues.Add("strategy", "crop");
                    switch (options.CropMode)
                    {
                    case CrunchOptions.cropmode.top:
                        resizevalues.Add("crop_mode", "top");
                        break;

                    case CrunchOptions.cropmode.northwest:
                        resizevalues.Add("crop_mode", "northwest");
                        break;

                    case CrunchOptions.cropmode.northeast:
                        resizevalues.Add("crop_mode", "northeast");
                        break;

                    case CrunchOptions.cropmode.west:
                        resizevalues.Add("crop_mode", "west");
                        break;

                    case CrunchOptions.cropmode.east:
                        resizevalues.Add("crop_mode", "east");
                        break;

                    case CrunchOptions.cropmode.southeast:
                        resizevalues.Add("crop_mode", "southeast");
                        break;

                    case CrunchOptions.cropmode.southwest:
                        resizevalues.Add("crop_mode", "southwest");
                        break;

                    case CrunchOptions.cropmode.south:
                        resizevalues.Add("crop_mode", "south");
                        break;

                    default:
                        resizevalues.Add("crop_mode", "center");
                        break;
                    }
                    break;

                case CrunchOptions.strategy.exact:
                    resizevalues.Add("strategy", "exact");
                    break;

                case CrunchOptions.strategy.fit:
                    resizevalues.Add("strategy", "fit");
                    break;

                case CrunchOptions.strategy.fill:
                    resizevalues.Add("strategy", "fill");
                    resizevalues.Add("background", options.background);
                    break;

                default:
                    resizevalues.Add("strategy", "auto");
                    break;
                }
                if (options.enhance)
                {
                    resizevalues.Add("enhance", options.enhance);
                }
            }
            #endregion

            #region WebP Compression
            if (options.webp)
            {
                parent.Add("webp", options.webp);
            }
            #endregion

            if (imageConversion != null)
            {
                parent.Add("convert", imageConversion);
            }
            if (resizevalues != null)
            {
                parent.Add("resize", resizevalues);
            }

            var stringContent = new StringContent(parent.ToString());

            content.Add(stringContent, "woop");
            var streamContent = new StreamContent(stream);
            //streamContent.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
            content.Add(streamContent, "file ", options.fullname);

            HttpResponseMessage postAsync = client.PostAsync("https://api.kraken.io/v1/upload", content).Result;

            Response jsonResult = null;
            if (postAsync.IsSuccessStatusCode)
            {
                string stringResult = postAsync.Content.ReadAsStringAsync().Result;

                var dynamicResult = JsonValue.Parse(stringResult);
                if (dynamicResult.ContainsKey("success") && dynamicResult["success"].ReadAs(false))
                {
                    jsonResult = postAsync.Content.ReadAsAsync <Response>().Result;
                }
                else
                {
                    throw new Exception(string.Format("Error: {0}", dynamicResult.GetValue("error").ReadAs <string>()));
                }
            }
            else
            {
                return(null);
            }

            HttpResponseMessage httpResponseMessage = client.GetAsync(jsonResult.Dest, HttpCompletionOption.ResponseHeadersRead).Result;

            if (!httpResponseMessage.IsSuccessStatusCode)
            {
                return(null);
            }

            Stream result = httpResponseMessage.Content.ReadAsStreamAsync().Result;

            var returnObject = new Entities.CrunchResult();
            returnObject.FileStream = result;
            returnObject.Format     = Path.GetExtension(jsonResult.Dest);

            return(returnObject);
        }