Beispiel #1
0
        public override ImageInfo GenerateImage(NameValueCollection parameters, string imgFile)
        {
            // Add image generation logic here and return an instance of ImageInfo
            var bgColor = Color.White;

            ContentType = ImageFormat.Jpeg;

            try
            {
                // Do we override caching for this image ?
                if (!string.IsNullOrEmpty(parameters ["nocache"]))
                {
                    Settings.EnableClientCache = false;
                    Settings.EnableServerCache = false;
                }

                // override cache time for single image
                if (!string.IsNullOrEmpty(parameters ["cacheexpiration"]))
                {
                    Settings.SetCacheExpiration(new TimeSpan(0, 0, Convert.ToInt32(parameters ["cacheexpiration"])));
                }

                // Do we have a default image file ?
                if (!string.IsNullOrEmpty(parameters ["defaultimage"]))
                {
                    defaultImageFile = parameters ["defaultimage"];
                }

                /*
                 * // Lets determine the 3 types of Image Source
                 * // TODO: Move this code to function GetImageFilename(NameValueCollection parameters)
                 * if (!string.IsNullOrEmpty (parameters ["file"]))
                 * {
                 *      imgFile = parameters ["file"].Trim ();
                 *
                 *      if (!File.Exists (imgFile))
                 *      {
                 *              imgFile = Path.GetFullPath (HttpContext.Current.Request.PhysicalApplicationPath + imgFile);
                 *              if (!File.Exists (imgFile))
                 *                      return new ImageInfo (EmptyImage);
                 *      }
                 * }
                 * // REVIEW: Remove path+index option?
                 * else if (!string.IsNullOrEmpty (parameters ["path"]))
                 * {
                 *      imgIndex = Convert.ToInt32 (parameters ["index"]);
                 *      imgPath = parameters ["path"];
                 *
                 *      if (!Directory.Exists (imgPath))
                 *      {
                 *              imgPath = Path.GetFullPath (HttpContext.Current.Request.PhysicalApplicationPath + imgPath);
                 *              if (!Directory.Exists (imgPath))
                 *                      return new ImageInfo (EmptyImage);
                 *      }
                 *
                 *      var Files = Directory.GetFiles (imgPath, "*");
                 *      if (Files.Length > 0 && Files.Length - 1 >= imgIndex)
                 *      {
                 *              Array.Sort (Files);
                 *              imgFile = Files [imgIndex];
                 *              if (File.Exists (imgFile) != true)
                 *                      return new ImageInfo (EmptyImage);
                 *      }
                 * }
                 * else if (string.IsNullOrEmpty (parameters ["url"]) &&
                 *       string.IsNullOrEmpty (parameters ["imageurl"]) &&
                 *       string.IsNullOrEmpty (parameters ["db"]) &&
                 *       string.IsNullOrEmpty (parameters ["fileid"]) &&
                 *       string.IsNullOrEmpty (parameters ["fileticket"]) &&
                 *       string.IsNullOrEmpty (parameters ["dnn"]) &&
                 *       string.IsNullOrEmpty (parameters ["percentage"]) &&
                 *       string.IsNullOrEmpty (parameters ["placeholder"]) &&
                 *       string.IsNullOrEmpty (parameters ["barcode"]) &&
                 *       string.IsNullOrEmpty (parameters ["schedule"]))
                 * {
                 *      return new ImageInfo (EmptyImage);
                 * }
                 */

                if (imgFile == string.Empty &&
                    string.IsNullOrEmpty(parameters ["url"]) &&
                    string.IsNullOrEmpty(parameters ["imageurl"]) &&
                    string.IsNullOrEmpty(parameters ["db"]) &&
                    string.IsNullOrEmpty(parameters ["dnn"]) &&
                    string.IsNullOrEmpty(parameters ["percentage"]) &&
                    string.IsNullOrEmpty(parameters ["placeholder"]) &&
                    string.IsNullOrEmpty(parameters ["barcode"]) &&
                    string.IsNullOrEmpty(parameters ["schedule"]))
                {
                    return(new ImageInfo(EmptyImage));
                }

                // We need to determine the output format
                if (!string.IsNullOrEmpty(parameters ["format"]))
                {
                    ContentType = Utils.GetImageFormatByExtension(parameters ["format"]);
                    if (ContentType == null)
                    {
                        return(new ImageInfo(EmptyImage));
                    }
                }
                else if (imgFile != string.Empty)
                {
                    var fi = new System.IO.FileInfo(imgFile);

                    ContentType = Utils.GetImageFormatByExtension(fi.Extension);
                    if (ContentType == null)
                    {
                        return(new ImageInfo(EmptyImage));
                    }
                }

                // determine background color
                if (!string.IsNullOrEmpty(parameters ["bgcolor"]))
                {
                    var color = parameters ["bgcolor"];
                    bgColor = color.StartsWith("#") ? ColorTranslator.FromHtml(color) : Color.FromName(color);
                }
            }
            catch (SecurityException)
            {
                if (Settings.EnableSecurityExceptions)
                {
                    throw;
                }
            }
            catch (Exception)
            {
                return(new ImageInfo(EmptyImage));
            }

            // Db Transform
            if (!string.IsNullOrEmpty(parameters ["db"]))
            {
                // First let us check if the Db value is a key or a connectionstring name

                var    settings = ConfigurationManager.AppSettings [parameters ["db"]];
                string connectionName = "", table = "", imageField = "", idField = "";
                if (!string.IsNullOrEmpty(settings))
                {
                    var values = settings.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                    foreach (var value in values)
                    {
                        var setting = value.Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries);
                        var name    = setting [0].ToLowerInvariant();
                        switch (name)
                        {
                        case "connectionstring":
                            connectionName = setting [1];
                            break;

                        case "table":
                            table = setting [1];
                            break;

                        case "imagefield":
                            imageField = setting [1];
                            break;

                        case "idfield":
                            idField = setting [1];
                            break;

                        default:
                            break;
                        }
                    }
                }

                var dbTrans = new ImageDbTransform();

                dbTrans.InterpolationMode  = Settings.InterpolationMode;
                dbTrans.PixelOffsetMode    = Settings.PixelOffsetMode;
                dbTrans.SmoothingMode      = Settings.SmoothingMode;
                dbTrans.CompositingQuality = Settings.CompositingQuality;

                /*
                 * dbTrans.InterpolationMode = InterpolationMode.HighQualityBicubic;
                 * dbTrans.PixelOffsetMode = PixelOffsetMode.HighQuality;
                 * dbTrans.SmoothingMode = SmoothingMode.HighQuality;
                 * dbTrans.CompositingQuality = CompositingQuality.HighQuality;*/


                if (connectionName == string.Empty || table == string.Empty || imageField == string.Empty || idField == string.Empty)
                {
                    connectionName = parameters ["db"];
                    table          = parameters ["table"];
                    imageField     = parameters ["imagefield"];
                    idField        = parameters ["idfield"];
                }

                var conn = ConfigurationManager.ConnectionStrings [connectionName];

                if (conn == null || string.IsNullOrEmpty(table) || string.IsNullOrEmpty(idField) ||
                    string.IsNullOrEmpty(parameters ["IdValue"]) || string.IsNullOrEmpty(imageField))
                {
                    return(new ImageInfo(EmptyImage));
                }

                dbTrans.ConnectionString = conn.ConnectionString;
                dbTrans.Table            = table;
                dbTrans.IdFieldName      = idField;
                dbTrans.IdFieldValue     = Convert.ToInt32(parameters ["idvalue"]);
                dbTrans.ImageFieldName   = imageField;
                dbTrans.EmptyImage       = EmptyImage;
                ImageTransforms.Add(dbTrans);
            }


            /*
             * // DNN FileId & Fileticket
             * if (!string.IsNullOrEmpty (parameters ["fileid"]) || !string.IsNullOrEmpty (parameters ["fileticket"]))
             * {
             *      // TODO: Check current user permissions to view this file
             *
             *      int fileId;
             *
             *      if (!string.IsNullOrEmpty (parameters ["fileticket"]))
             *      {
             *              // get fileId from fileticket value
             *              fileId = FileLinkClickController.Instance.GetFileIdFromLinkClick (parameters);
             *      }
             *      else
             *      {
             *              // check if fileid is integer
             *              if (!int.TryParse (parameters ["fileid"], out fileId))
             *                      return new ImageInfo (EmptyImage);
             *      }
             *
             *      // check if we really have such file in a DB
             *      var fileInfo = FileManager.Instance.GetFile (fileId);
             *      if (fileInfo == null)
             *              return new ImageInfo (EmptyImage);
             *
             *      // check if file exists
             *      if (!File.Exists (fileInfo.PhysicalPath))
             *              return new ImageInfo (EmptyImage);
             *
             *      // determine output format
             *      // REVIEW: Is this conflicts with Format parameter?
             *
             *      imgFile = fileInfo.PhysicalPath;
             * } */

            // DNN Profile Pic
            // TODO: Refactor this to more tight integration with DNN
            if (!string.IsNullOrEmpty(parameters ["dnn"]))
            {
                //First let us check if the Db value is a key or a connectionstring name

                var userId = Null.NullInteger;
                if (!string.IsNullOrEmpty(parameters ["userid"]))
                {
                    userId = Convert.ToInt32(parameters ["userid"]);
                }

                var portalId = Null.NullInteger;
                if (!string.IsNullOrEmpty(parameters ["portalid"]))
                {
                    portalId = Convert.ToInt32(parameters ["portalid"]);
                }

                var dbTrans = new ImageDbTransform();

                /*
                 *              dbTrans.InterpolationMode = InterpolationMode.HighQualityBicubic;
                 *              dbTrans.PixelOffsetMode = PixelOffsetMode.HighQuality;
                 *              dbTrans.SmoothingMode = SmoothingMode.HighQuality;
                 *              dbTrans.CompositingQuality = CompositingQuality.HighQuality;*/

                dbTrans.InterpolationMode  = Settings.InterpolationMode;
                dbTrans.PixelOffsetMode    = Settings.PixelOffsetMode;
                dbTrans.SmoothingMode      = Settings.SmoothingMode;
                dbTrans.CompositingQuality = Settings.CompositingQuality;

                var connectionName = "SiteSqlServer";                 // DNN

                var conn = ConfigurationManager.ConnectionStrings [connectionName];

                if (conn == null || string.IsNullOrEmpty((parameters ["portalid"])) &&
                    string.IsNullOrEmpty(parameters ["userid"]))
                {
                    return(new ImageInfo(EmptyImage));
                }

                dbTrans.ConnectionString = conn.ConnectionString;
                dbTrans.UserId           = userId;
                dbTrans.PortalId         = portalId;
                dbTrans.EmptyImage       = EmptyImage;

                ImageTransforms.Add(dbTrans);
            }

            // Url Transform
            if (!string.IsNullOrEmpty(parameters ["url"]))
            {
                var urlTrans = new ImageUrlTransform();

                urlTrans.InterpolationMode  = Settings.InterpolationMode;
                urlTrans.PixelOffsetMode    = Settings.PixelOffsetMode;
                urlTrans.SmoothingMode      = Settings.SmoothingMode;
                urlTrans.CompositingQuality = Settings.CompositingQuality;

                /*
                 * urlTrans.InterpolationMode = InterpolationMode.HighQualityBicubic;
                 * urlTrans.PixelOffsetMode = PixelOffsetMode.HighQuality;
                 * urlTrans.SmoothingMode = SmoothingMode.HighQuality;
                 * urlTrans.CompositingQuality = CompositingQuality.HighQuality;*/

                urlTrans.Url = parameters ["url"];
                if (!String.IsNullOrEmpty(parameters ["ratio"]))
                {
                    urlTrans.Ratio = (UrlRatioMode)Enum.Parse(typeof(UrlRatioMode), parameters ["ratio"], true);
                }
                else
                {
                    urlTrans.Ratio = UrlRatioMode.Full;
                }

                ImageTransforms.Add(urlTrans);
            }

            // ImageUrl Transform
            if (!string.IsNullOrEmpty(parameters ["imageurl"]))
            {
                var imageUrlTrans = new ImageUrlImageTransform();

                imageUrlTrans.InterpolationMode  = Settings.InterpolationMode;
                imageUrlTrans.PixelOffsetMode    = Settings.PixelOffsetMode;
                imageUrlTrans.SmoothingMode      = Settings.SmoothingMode;
                imageUrlTrans.CompositingQuality = Settings.CompositingQuality;

                /*
                 * imageUrlTrans.InterpolationMode = InterpolationMode.HighQualityBicubic;
                 * imageUrlTrans.PixelOffsetMode = PixelOffsetMode.HighQuality;
                 * imageUrlTrans.SmoothingMode = SmoothingMode.HighQuality;
                 * imageUrlTrans.CompositingQuality = CompositingQuality.HighQuality;*/

                imageUrlTrans.ImageUrl = parameters ["imageurl"];

                ImageTransforms.Add(imageUrlTrans);
            }

            // Counter Transform
            if (!string.IsNullOrEmpty(parameters ["counter"]))
            {
                var counterTrans = new ImageCounterTransform();

                counterTrans.InterpolationMode  = Settings.InterpolationMode;
                counterTrans.PixelOffsetMode    = Settings.PixelOffsetMode;
                counterTrans.SmoothingMode      = Settings.SmoothingMode;
                counterTrans.CompositingQuality = Settings.CompositingQuality;

                /*
                 * counterTrans.InterpolationMode = InterpolationMode.HighQualityBicubic;
                 * counterTrans.PixelOffsetMode = PixelOffsetMode.HighQuality;
                 * counterTrans.SmoothingMode = SmoothingMode.HighQuality;
                 * counterTrans.CompositingQuality = CompositingQuality.HighQuality;
                 */

                if (!string.IsNullOrEmpty(parameters ["counter"]))
                {
                    counterTrans.Counter = Convert.ToInt32(parameters ["counter"]);
                }
                if (!string.IsNullOrEmpty(parameters ["digits"]))
                {
                    counterTrans.Digits = Convert.ToInt32(parameters ["digits"]);
                }

                ImageTransforms.Add(counterTrans);
            }

            // Radial Indicator
            if (!string.IsNullOrEmpty((parameters ["percentage"])))
            {
                var percentTrans = new ImagePercentageTransform();

                /*
                 * percentTrans.InterpolationMode = InterpolationMode.HighQualityBicubic;
                 * percentTrans.PixelOffsetMode = PixelOffsetMode.HighQuality;
                 * percentTrans.SmoothingMode = SmoothingMode.HighQuality;
                 * percentTrans.CompositingQuality = CompositingQuality.HighQuality;
                 */

                percentTrans.InterpolationMode  = Settings.InterpolationMode;
                percentTrans.PixelOffsetMode    = Settings.PixelOffsetMode;
                percentTrans.SmoothingMode      = Settings.SmoothingMode;
                percentTrans.CompositingQuality = Settings.CompositingQuality;

                if (!string.IsNullOrEmpty(parameters ["Percentage"]))
                {
                    percentTrans.Percentage = Convert.ToInt32(parameters ["Percentage"]);
                }
                if (!string.IsNullOrEmpty(parameters ["BgColor"]))
                {
                    percentTrans.Color = bgColor;
                }
                else
                {
                    percentTrans.Color = Color.Orange;
                }

                ImageTransforms.Add(percentTrans);
            }

            // Barcode
            if (!string.IsNullOrEmpty((parameters ["barcode"])))
            {
                var barcodeTrans = new ImageBarcodeTransform();

                /*
                 * barcodeTrans.InterpolationMode = InterpolationMode.HighQualityBicubic;
                 * barcodeTrans.PixelOffsetMode = PixelOffsetMode.HighQuality;
                 * barcodeTrans.SmoothingMode = SmoothingMode.HighQuality;
                 * barcodeTrans.CompositingQuality = CompositingQuality.HighQuality;
                 */

                barcodeTrans.InterpolationMode  = Settings.InterpolationMode;
                barcodeTrans.PixelOffsetMode    = Settings.PixelOffsetMode;
                barcodeTrans.SmoothingMode      = Settings.SmoothingMode;
                barcodeTrans.CompositingQuality = Settings.CompositingQuality;

                barcodeTrans.Border = 0;
                barcodeTrans.Width  = 100;
                barcodeTrans.Height = 100;

                if (!string.IsNullOrEmpty(parameters ["encoding"]))
                {
                    barcodeTrans.Encoding = parameters ["encoding"];
                }

                if (!string.IsNullOrEmpty(parameters ["type"]) &&
                    "upca,ean8,ean13,code39,code128,itf,codabar,plessey,msi,qrcode,pdf417,aztec,datamatrix,".LastIndexOf(parameters ["type"].ToLowerInvariant() + ",") > -1)
                {
                    barcodeTrans.Type = parameters ["type"].ToLower();
                }
                if (!string.IsNullOrEmpty(parameters ["content"]))
                {
                    barcodeTrans.Content = HttpUtility.UrlDecode(parameters ["content"]);
                }
                if (!string.IsNullOrEmpty(parameters ["w"]))
                {
                    barcodeTrans.Width = Convert.ToInt32(parameters ["w"]);
                }
                else if (!string.IsNullOrEmpty(parameters ["width"]))
                {
                    barcodeTrans.Width = Convert.ToInt32(parameters ["width"]);
                }
                if (!string.IsNullOrEmpty(parameters ["h"]))
                {
                    barcodeTrans.Height = Convert.ToInt32(parameters ["h"]);
                }
                else if (!string.IsNullOrEmpty(parameters ["height"]))
                {
                    barcodeTrans.Height = Convert.ToInt32(parameters ["height"]);
                }
                if (!string.IsNullOrEmpty(parameters ["border"]))
                {
                    barcodeTrans.Border = Convert.ToInt32(parameters ["border"]);
                }

                ImageTransforms.Add(barcodeTrans);
            }

            if (!string.IsNullOrEmpty((parameters ["schedule"])))
            {
                var scheduleTrans = new ImageScheduleTransform();

                /*
                 * scheduleTrans.InterpolationMode = InterpolationMode.HighQualityBicubic;
                 * scheduleTrans.PixelOffsetMode = PixelOffsetMode.HighQuality;
                 * scheduleTrans.SmoothingMode = SmoothingMode.HighQuality;
                 * scheduleTrans.CompositingQuality = CompositingQuality.HighQuality;
                 */

                scheduleTrans.InterpolationMode  = Settings.InterpolationMode;
                scheduleTrans.PixelOffsetMode    = Settings.PixelOffsetMode;
                scheduleTrans.SmoothingMode      = Settings.SmoothingMode;
                scheduleTrans.CompositingQuality = Settings.CompositingQuality;

                scheduleTrans.Matrix = parameters ["matrix"];

                // determine culture
                if (!string.IsNullOrEmpty(parameters ["culture"]))
                {
                    scheduleTrans.Culture = parameters ["culture"];
                }
                else
                {
                    scheduleTrans.Culture = Thread.CurrentThread.CurrentCulture.Name;
                }

                // determine bgcolor
                if (!string.IsNullOrEmpty(parameters ["bgcolor"]))
                {
                    scheduleTrans.BackColor = bgColor;
                }
                else
                {
                    scheduleTrans.BackColor = Color.White;
                }

                ImageTransforms.Add(scheduleTrans);
            }

            // Resize-Transformation (only if not placeholder or barcode)
            if (string.IsNullOrEmpty(parameters ["placeholder"]) && string.IsNullOrEmpty(parameters ["barcode"]) &&
                (!string.IsNullOrEmpty(parameters ["w"]) || !string.IsNullOrEmpty(parameters ["h"]) ||
                 (!string.IsNullOrEmpty(parameters ["width"]) || !string.IsNullOrEmpty(parameters ["height"]) ||
                  (!string.IsNullOrEmpty(parameters ["maxwidth"]) || !string.IsNullOrEmpty(parameters ["maxheight"])))))
            {
                var resizeTrans = new ImageResizeTransform();
                resizeTrans.Mode = ImageResizeMode.Fit;

                resizeTrans.InterpolationMode  = Settings.InterpolationMode;
                resizeTrans.PixelOffsetMode    = Settings.PixelOffsetMode;
                resizeTrans.SmoothingMode      = Settings.SmoothingMode;
                resizeTrans.CompositingQuality = Settings.CompositingQuality;

                /*
                 * resizeTrans.InterpolationMode = InterpolationMode.HighQualityBicubic;
                 * resizeTrans.PixelOffsetMode = PixelOffsetMode.HighQuality;
                 * resizeTrans.SmoothingMode = SmoothingMode.HighQuality;
                 * resizeTrans.CompositingQuality = CompositingQuality.HighQuality;
                 */
                resizeTrans.BackColor = bgColor;

                // Parameter 'Mode' is obsolete. New is 'ResizeMode'
                // if (!string.IsNullOrEmpty(parameters["Mode"]))
                //	resizeTrans.Mode = (ImageResizeMode) Enum.Parse(typeof (ImageResizeMode), parameters["Mode"]);

                if (!string.IsNullOrEmpty(parameters ["resizemode"]))
                {
                    // TODO: Use Enum.TryParse and fallback resize mode
                    resizeTrans.Mode = (ImageResizeMode)Enum.Parse(typeof(ImageResizeMode), parameters ["resizemode"], true);
                }

                if (!string.IsNullOrEmpty(parameters ["w"]))
                {
                    resizeTrans.Width = Convert.ToInt32(parameters ["w"]);
                }
                else if (!string.IsNullOrEmpty(parameters ["width"]))
                {
                    resizeTrans.Width = Convert.ToInt32(parameters ["width"]);
                }

                if (!string.IsNullOrEmpty(parameters ["h"]))
                {
                    resizeTrans.Height = Convert.ToInt32(parameters ["h"]);
                }
                else if (!string.IsNullOrEmpty(parameters ["height"]))
                {
                    resizeTrans.Height = Convert.ToInt32(parameters ["height"]);
                }

                if (!string.IsNullOrEmpty(parameters ["maxwidth"]))
                {
                    resizeTrans.MaxWidth = Convert.ToInt32(parameters ["maxwidth"]);
                }
                if (!string.IsNullOrEmpty(parameters ["maxheight"]))
                {
                    resizeTrans.MaxHeight = Convert.ToInt32(parameters ["maxheight"]);
                }
                if (!string.IsNullOrEmpty(parameters ["border"]))
                {
                    resizeTrans.Border = Convert.ToInt32(parameters ["border"]);
                }

                ImageTransforms.Add(resizeTrans);
            }

            // Watermark Transform
            if (!string.IsNullOrEmpty(parameters ["watermarktext"]))
            {
                var watermarkTrans = new ImageWatermarkTransform();

                watermarkTrans.InterpolationMode  = Settings.InterpolationMode;
                watermarkTrans.PixelOffsetMode    = Settings.PixelOffsetMode;
                watermarkTrans.SmoothingMode      = Settings.SmoothingMode;
                watermarkTrans.CompositingQuality = Settings.CompositingQuality;

                /*
                 * watermarkTrans.InterpolationMode = InterpolationMode.HighQualityBicubic;
                 * watermarkTrans.PixelOffsetMode = PixelOffsetMode.HighQuality;
                 * watermarkTrans.SmoothingMode = SmoothingMode.HighQuality;
                 * watermarkTrans.CompositingQuality = CompositingQuality.HighQuality;
                 */

                watermarkTrans.WatermarkText = parameters ["watermarktext"];
                if (!string.IsNullOrEmpty(parameters ["watermarkfontfamily"]))
                {
                    watermarkTrans.FontFamily = parameters ["watermarkfontfamily"];
                }
                if (!string.IsNullOrEmpty(parameters ["watermarkfontcolor"]))
                {
                    var color = parameters ["watermarkfontcolor"];
                    watermarkTrans.FontColor = color.StartsWith("#") ? ColorTranslator.FromHtml(color) : Color.FromName(color);
                }
                if (!string.IsNullOrEmpty(parameters ["watermarkfontsize"]))
                {
                    watermarkTrans.FontSize = Convert.ToSingle(parameters ["watermarkfontsize"]);
                }
                if (!string.IsNullOrEmpty(parameters ["watermarkposition"]))
                {
                    var enumType = typeof(WatermarkPositionMode);
                    var pos      = parameters ["watermarkposition"];
                    watermarkTrans.WatermarkPosition = (WatermarkPositionMode)Enum.Parse(enumType, pos, true);
                }
                if (!string.IsNullOrEmpty(parameters ["watermarkopacity"]))
                {
                    watermarkTrans.WatermarkOpacity = Convert.ToInt32(parameters ["watermarkopacity"]);
                }

                ImageTransforms.Add(watermarkTrans);
            }

            // Gamma adjustment
            if (!string.IsNullOrEmpty(parameters ["gamma"]))
            {
                var gammaTrans = new ImageGammaTransform();

                gammaTrans.InterpolationMode  = Settings.InterpolationMode;
                gammaTrans.PixelOffsetMode    = Settings.PixelOffsetMode;
                gammaTrans.SmoothingMode      = Settings.SmoothingMode;
                gammaTrans.CompositingQuality = Settings.CompositingQuality;

                /*
                 * gammaTrans.InterpolationMode = InterpolationMode.HighQualityBicubic;
                 * gammaTrans.PixelOffsetMode = PixelOffsetMode.HighQuality;
                 * gammaTrans.SmoothingMode = SmoothingMode.HighQuality;
                 * gammaTrans.CompositingQuality = CompositingQuality.HighQuality;
                 */
                var gamma = 1.0;

                if (double.TryParse(parameters ["Gamma"], NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out gamma) && (gamma >= 0.2 && gamma <= 5))
                {
                    gammaTrans.Gamma = gamma;
                    ImageTransforms.Add(gammaTrans);
                }
            }

            // Brightness adjustment
            if (!string.IsNullOrEmpty(parameters ["brightness"]))
            {
                var brightnessTrans = new ImageBrightnessTransform();

                /*
                 * brightnessTrans.InterpolationMode = InterpolationMode.HighQualityBicubic;
                 * brightnessTrans.PixelOffsetMode = PixelOffsetMode.HighQuality;
                 * brightnessTrans.SmoothingMode = SmoothingMode.HighQuality;
                 * brightnessTrans.CompositingQuality = CompositingQuality.HighQuality;
                 */
                brightnessTrans.InterpolationMode  = Settings.InterpolationMode;
                brightnessTrans.PixelOffsetMode    = Settings.PixelOffsetMode;
                brightnessTrans.SmoothingMode      = Settings.SmoothingMode;
                brightnessTrans.CompositingQuality = Settings.CompositingQuality;

                var brightness = 0;

                if (int.TryParse(parameters ["brightness"], out brightness))
                {
                    brightnessTrans.Brightness = brightness;
                    ImageTransforms.Add(brightnessTrans);
                }
            }

            // Contrast adjustment
            if (!string.IsNullOrEmpty(parameters ["contrast"]))
            {
                var contrastTrans = new ImageContrastTransform();

                /*
                 * contrastTrans.InterpolationMode = InterpolationMode.HighQualityBicubic;
                 * contrastTrans.PixelOffsetMode = PixelOffsetMode.HighQuality;
                 * contrastTrans.SmoothingMode = SmoothingMode.HighQuality;
                 * contrastTrans.CompositingQuality = CompositingQuality.HighQuality;
                 */

                contrastTrans.InterpolationMode  = Settings.InterpolationMode;
                contrastTrans.PixelOffsetMode    = Settings.PixelOffsetMode;
                contrastTrans.SmoothingMode      = Settings.SmoothingMode;
                contrastTrans.CompositingQuality = Settings.CompositingQuality;

                var contrast = 0.0;

                if (double.TryParse(parameters ["contrast"], NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out contrast) && (contrast >= -100 && contrast <= 100))
                {
                    contrastTrans.Contrast = contrast;
                    ImageTransforms.Add(contrastTrans);
                }
            }

            // Greyscale
            if (!string.IsNullOrEmpty(parameters ["greyscale"]))
            {
                var greyscaleTrans = new ImageGreyScaleTransform();

                greyscaleTrans.InterpolationMode  = InterpolationMode.HighQualityBicubic;
                greyscaleTrans.PixelOffsetMode    = PixelOffsetMode.HighQuality;
                greyscaleTrans.SmoothingMode      = SmoothingMode.HighQuality;
                greyscaleTrans.CompositingQuality = CompositingQuality.HighQuality;

                /*
                 * greyscaleTrans.InterpolationMode = InterpolationMode.HighQualityBicubic;
                 * greyscaleTrans.PixelOffsetMode = PixelOffsetMode.HighQuality;
                 * greyscaleTrans.SmoothingMode = SmoothingMode.HighQuality;
                 * greyscaleTrans.CompositingQuality = CompositingQuality.HighQuality;
                 */
                ImageTransforms.Add(greyscaleTrans);
            }

            // Invert
            if (!string.IsNullOrEmpty(parameters ["invert"]))
            {
                var invertTrans = new ImageInvertTransform();

                invertTrans.InterpolationMode  = InterpolationMode.HighQualityBicubic;
                invertTrans.PixelOffsetMode    = PixelOffsetMode.HighQuality;
                invertTrans.SmoothingMode      = SmoothingMode.HighQuality;
                invertTrans.CompositingQuality = CompositingQuality.HighQuality;

                /*
                 * invertTrans.InterpolationMode = InterpolationMode.HighQualityBicubic;
                 * invertTrans.PixelOffsetMode = PixelOffsetMode.HighQuality;
                 * invertTrans.SmoothingMode = SmoothingMode.HighQuality;
                 * invertTrans.CompositingQuality = CompositingQuality.HighQuality;*/
                ImageTransforms.Add(invertTrans);
            }

            // Rotate / Flip
            if (!string.IsNullOrEmpty(parameters ["rotateflip"]))
            {
                var rotateFlipTrans = new ImageRotateFlipTransform();

                rotateFlipTrans.InterpolationMode  = InterpolationMode.HighQualityBicubic;
                rotateFlipTrans.PixelOffsetMode    = PixelOffsetMode.HighQuality;
                rotateFlipTrans.SmoothingMode      = SmoothingMode.HighQuality;
                rotateFlipTrans.CompositingQuality = CompositingQuality.HighQuality;

                /*
                 * rotateFlipTrans.InterpolationMode = InterpolationMode.HighQualityBicubic;
                 * rotateFlipTrans.PixelOffsetMode = PixelOffsetMode.HighQuality;
                 * rotateFlipTrans.SmoothingMode = SmoothingMode.HighQuality;
                 * rotateFlipTrans.CompositingQuality = CompositingQuality.HighQuality;
                 */

                var rotateFlipType = (RotateFlipType)Enum.Parse(typeof(RotateFlipType), parameters ["RotateFlip"]);
                rotateFlipTrans.RotateFlip = rotateFlipType;

                ImageTransforms.Add(rotateFlipTrans);
            }

            // Placeholder
            if (!string.IsNullOrEmpty(parameters ["placeholder"]))
            {
                var placeHolderTrans = new ImagePlaceholderTransform();

                /*
                 * placeHolderTrans.InterpolationMode = InterpolationMode.HighQualityBicubic;
                 * placeHolderTrans.PixelOffsetMode = PixelOffsetMode.HighQuality;
                 * placeHolderTrans.SmoothingMode = SmoothingMode.HighQuality;
                 * placeHolderTrans.CompositingQuality = CompositingQuality.HighQuality;*/

                placeHolderTrans.InterpolationMode  = InterpolationMode.HighQualityBicubic;
                placeHolderTrans.PixelOffsetMode    = PixelOffsetMode.HighQuality;
                placeHolderTrans.SmoothingMode      = SmoothingMode.HighQuality;
                placeHolderTrans.CompositingQuality = CompositingQuality.HighQuality;

                var width  = 0;
                var height = 0;

                if (!string.IsNullOrEmpty(parameters ["w"]))
                {
                    if (int.TryParse(parameters ["w"], out width))
                    {
                        placeHolderTrans.Width = width;
                    }
                }
                else if (!string.IsNullOrEmpty(parameters ["width"]))
                {
                    if (int.TryParse(parameters ["width"], out width))
                    {
                        placeHolderTrans.Width = width;
                    }
                }

                if (!string.IsNullOrEmpty(parameters ["h"]))
                {
                    if (int.TryParse(parameters ["h"], out height))
                    {
                        placeHolderTrans.Height = height;
                    }
                }
                else if (!string.IsNullOrEmpty(parameters ["height"]))
                {
                    if (int.TryParse(parameters ["height"], out height))
                    {
                        placeHolderTrans.Height = height;
                    }
                }

                if (!string.IsNullOrEmpty(parameters ["color"]))
                {
                    string color = parameters ["color"];
                    placeHolderTrans.Color = color.StartsWith("#") ? ColorTranslator.FromHtml(color) : Color.FromName(color);
                }

                if (!string.IsNullOrEmpty(parameters ["text"]))
                {
                    placeHolderTrans.Text = parameters ["text"];
                }

                if (!string.IsNullOrEmpty(parameters ["bgcolor"]))
                {
                    string color = parameters ["bgcolor"];
                    placeHolderTrans.BackColor = color.StartsWith("#") ? ColorTranslator.FromHtml(color) : Color.FromName(color);
                }

                ImageTransforms.Add(placeHolderTrans);
            }

            if (imgFile == string.Empty)
            {
                // REVIEW: Return new ImageInfo(EmptyImage)?
                var dummy = new Bitmap(1, 1, PixelFormat.Format24bppRgb);
                var ms    = new MemoryStream();
                dummy.Save(ms, ImageFormat.Jpeg);
                return(new ImageInfo(ms.ToArray()));
            }
            else
            {
                // read all data from file
                return(new ImageInfo(File.ReadAllBytes(imgFile)));
            }
        }
Beispiel #2
0
        // Add image generation logic here and return an instance of ImageInfo
        public override ImageInfo GenerateImage(NameValueCollection parameters)
        {
            SetupCulture();

            //which type of image should be generated ?
            string mode = string.IsNullOrEmpty(parameters["mode"]) ? "profilepic" : parameters["mode"].ToLowerInvariant();

            // We need to determine the output format
            string format = string.IsNullOrEmpty(parameters["format"]) ? "jpg" : parameters["format"].ToLowerInvariant();

            // Lets retrieve the color
            Color color     = string.IsNullOrEmpty(parameters["color"]) ? Color.White : (parameters["color"].StartsWith("#") ? ColorTranslator.FromHtml(parameters["color"]) : Color.FromName(parameters["color"]));
            Color backColor = string.IsNullOrEmpty(parameters["backcolor"]) ? Color.White : (parameters["backcolor"].StartsWith("#") ? ColorTranslator.FromHtml(parameters["backcolor"]) : Color.FromName(parameters["backcolor"]));

            // Do we have a border ?
            int border = string.IsNullOrEmpty(parameters["border"]) ? 0 : Convert.ToInt32(parameters["border"]);

            // Do we have a resizemode defined ?
            var resizeMode = string.IsNullOrEmpty(parameters["resizemode"]) ? ImageResizeMode.Fit : (ImageResizeMode)Enum.Parse(typeof(ImageResizeMode), parameters["ResizeMode"], true);

            // Maximum sizes
            int maxWidth  = string.IsNullOrEmpty(parameters["MaxWidth"]) ? 0 : Convert.ToInt32(parameters["MaxWidth"]);
            int maxHeight = string.IsNullOrEmpty(parameters["MaxHeight"]) ? 0 : Convert.ToInt32(parameters["MaxHeight"]);

            // Any text ?
            string text = string.IsNullOrEmpty(parameters["text"]) ? "" : parameters["text"];

            // Default Image
            _defaultImageFile = string.IsNullOrEmpty(parameters["NoImage"]) ? string.Empty : parameters["NoImage"];

            // Do we override caching for this image ?
            if (!string.IsNullOrEmpty(parameters["NoCache"]))
            {
                EnableClientCache = false;
                EnableServerCache = false;
            }

            try
            {
                ContentType = GetImageFormat(format);

                switch (mode)
                {
                case "profilepic":
                    int uid;
                    if (!int.TryParse(parameters["userid"], out uid) || uid <= 0)
                    {
                        uid = -1;
                    }
                    var uppTrans = new UserProfilePicTransform
                    {
                        UserID = uid
                    };

                    IFileInfo photoFile;
                    ContentType = !uppTrans.TryGetPhotoFile(out photoFile)
                            ? ImageFormat.Gif
                            : GetImageFormat(photoFile?.Extension ?? "jpg");

                    ImageTransforms.Add(uppTrans);
                    break;

                case "placeholder":
                    var placeHolderTrans = new PlaceholderTransform();
                    int width, height;
                    if (TryParseDimension(parameters["w"], out width))
                    {
                        placeHolderTrans.Width = width;
                    }
                    if (TryParseDimension(parameters["h"], out height))
                    {
                        placeHolderTrans.Height = height;
                    }
                    if (!string.IsNullOrEmpty(parameters["Color"]))
                    {
                        placeHolderTrans.Color = color;
                    }
                    if (!string.IsNullOrEmpty(parameters["Text"]))
                    {
                        placeHolderTrans.Text = text;
                    }
                    if (!string.IsNullOrEmpty(parameters["BackColor"]))
                    {
                        placeHolderTrans.BackColor = backColor;
                    }

                    ImageTransforms.Add(placeHolderTrans);
                    break;

                case "securefile":
                    var secureFileTrans = new SecureFileTransform();
                    if (!string.IsNullOrEmpty(parameters["FileId"]))
                    {
                        var fileId = Convert.ToInt32(parameters["FileId"]);
                        var file   = FileManager.Instance.GetFile(fileId);
                        if (file == null)
                        {
                            return(GetEmptyImageInfo());
                        }
                        var folder = FolderManager.Instance.GetFolder(file.FolderId);
                        if (!secureFileTrans.DoesHaveReadFolderPermission(folder))
                        {
                            return(GetEmptyImageInfo());
                        }
                        ContentType = GetImageFormat(file.Extension);
                        secureFileTrans.SecureFile = file;
                        secureFileTrans.EmptyImage = EmptyImage;
                        ImageTransforms.Add(secureFileTrans);
                    }
                    break;

                case "file":
                    var imgFile = string.Empty;
                    var imgUrl  = string.Empty;

                    // Lets determine the 2 types of Image Source: Single file, file url
                    var filePath = parameters["File"];
                    if (!string.IsNullOrEmpty(filePath))
                    {
                        filePath = filePath.Trim();
                        var fullFilePath = HttpContext.Current.Server.MapPath(filePath);
                        if (!File.Exists(fullFilePath) || !IsAllowedFilePathImage(filePath))
                        {
                            return(GetEmptyImageInfo());
                        }
                        imgFile = fullFilePath;
                    }
                    else if (!string.IsNullOrEmpty(parameters["Url"]))
                    {
                        var url = parameters["Url"];
                        // allow only site resources when using the url parameter
                        if (!url.StartsWith("http") || !UriBelongsToSite(new Uri(url)))
                        {
                            return(GetEmptyImageInfo());
                        }

                        imgUrl = url;
                    }

                    if (string.IsNullOrEmpty(parameters["format"]))
                    {
                        string extension;
                        if (string.IsNullOrEmpty(parameters["Url"]))
                        {
                            var fi = new System.IO.FileInfo(imgFile);
                            extension = fi.Extension.ToLowerInvariant();
                        }
                        else
                        {
                            string[] parts = parameters["Url"].Split('.');
                            extension = parts[parts.Length - 1].ToLowerInvariant();
                        }
                        ContentType = GetImageFormat(extension);
                    }
                    var imageFileTrans = new ImageFileTransform {
                        ImageFilePath = imgFile, ImageUrl = imgUrl
                    };
                    ImageTransforms.Add(imageFileTrans);
                    break;

                default:

                    string   imageTransformClass      = ConfigurationManager.AppSettings["DnnImageHandler." + mode];
                    string[] imageTransformClassParts = imageTransformClass.Split(',');
                    var      asm = Assembly.LoadFrom(Globals.ApplicationMapPath + @"\bin\" +
                                                     imageTransformClassParts[1].Trim() + ".dll");
                    var t = asm.GetType(imageTransformClassParts[0].Trim());
                    var imageTransform = (ImageTransform)Activator.CreateInstance(t);

                    foreach (var key in parameters.AllKeys)
                    {
                        var pi = t.GetProperty(key, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
                        if (pi != null && key != "mode")
                        {
                            switch (key.ToLowerInvariant())
                            {
                            case "color":
                                pi.SetValue(imageTransform, color, null);
                                break;

                            case "backcolor":
                                pi.SetValue(imageTransform, backColor, null);
                                break;

                            case "border":
                                pi.SetValue(imageTransform, border, null);
                                break;

                            default:
                                switch (pi.PropertyType.Name)
                                {
                                case "Int32":
                                    pi.SetValue(imageTransform, Convert.ToInt32(parameters[key]), null);
                                    break;

                                case "String":
                                    pi.SetValue(imageTransform, parameters[key], null);
                                    break;
                                }
                                break;
                            }
                        }
                    }
                    ImageTransforms.Add(imageTransform);
                    break;
                }
            }
            catch (Exception ex)
            {
                Exceptions.Exceptions.LogException(ex);
                return(GetEmptyImageInfo());
            }

            // Resize-Transformation
            if (mode != "placeholder")
            {
                int width, height;

                TryParseDimension(parameters["w"], out width);
                TryParseDimension(parameters["h"], out height);

                var size = string.IsNullOrEmpty(parameters["size"]) ? "" : parameters["size"];

                switch (size)
                {
                case "xxs":
                    width  = 16;
                    height = 16;
                    break;

                case "xs":
                    width  = 32;
                    height = 32;
                    break;

                case "s":
                    width  = 50;
                    height = 50;
                    break;

                case "l":
                    width  = 64;
                    height = 64;
                    break;

                case "xl":
                    width  = 128;
                    height = 128;
                    break;

                case "xxl":
                    width  = 256;
                    height = 256;
                    break;
                }

                if (mode == "profilepic")
                {
                    resizeMode = ImageResizeMode.FitSquare;
                    if (width > 0 && height > 0 && width != height)
                    {
                        resizeMode = ImageResizeMode.Fill;
                    }
                }

                if (width > 0 || height > 0)
                {
                    var resizeTrans = new ImageResizeTransform
                    {
                        Mode      = resizeMode,
                        BackColor = backColor,
                        Width     = width,
                        Height    = height,
                        MaxWidth  = maxWidth,
                        MaxHeight = maxHeight,
                        Border    = border
                    };
                    ImageTransforms.Add(resizeTrans);
                }
            }

            // Gamma adjustment
            if (!string.IsNullOrEmpty(parameters["Gamma"]))
            {
                var    gammaTrans = new ImageGammaTransform();
                double gamma;
                if (double.TryParse(parameters["Gamma"], NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out gamma) && gamma >= 0.2 && gamma <= 5)
                {
                    gammaTrans.Gamma = gamma;
                    ImageTransforms.Add(gammaTrans);
                }
            }

            // Brightness adjustment
            if (!string.IsNullOrEmpty(parameters["Brightness"]))
            {
                var brightnessTrans = new ImageBrightnessTransform();
                int brightness;
                if (int.TryParse(parameters["Brightness"], out brightness))
                {
                    brightnessTrans.Brightness = brightness;
                    ImageTransforms.Add(brightnessTrans);
                }
            }

            // Contrast adjustment
            if (!string.IsNullOrEmpty(parameters["Contrast"]))
            {
                var    contrastTrans = new ImageContrastTransform();
                double contrast;
                if (double.TryParse(parameters["Contrast"], NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out contrast) && (contrast >= -100 && contrast <= 100))
                {
                    contrastTrans.Contrast = contrast;
                    ImageTransforms.Add(contrastTrans);
                }
            }

            // Greyscale
            if (!string.IsNullOrEmpty(parameters["Greyscale"]))
            {
                var greyscaleTrans = new ImageGreyScaleTransform();
                ImageTransforms.Add(greyscaleTrans);
            }

            // Invert
            if (!string.IsNullOrEmpty(parameters["Invert"]))
            {
                var invertTrans = new ImageInvertTransform();
                ImageTransforms.Add(invertTrans);
            }

            // Rotate / Flip
            if (!string.IsNullOrEmpty(parameters["RotateFlip"]))
            {
                var rotateFlipTrans = new ImageRotateFlipTransform();
                var rotateFlipType  = (RotateFlipType)Enum.Parse(typeof(RotateFlipType), parameters["RotateFlip"]);
                rotateFlipTrans.RotateFlip = rotateFlipType;
                ImageTransforms.Add(rotateFlipTrans);
            }

            // We start the chain with an empty image
            var dummy = new Bitmap(1, 1);

            using (var ms = new MemoryStream())
            {
                dummy.Save(ms, ContentType);
                return(new ImageInfo(ms.ToArray()));
            }
        }