/// <summary>
 /// Initializes a new instance of the <see cref="ResizeLayer"/> class.
 /// </summary>
 /// <param name="size">
 /// The <see cref="T:System.Drawing.Size"/> containing the width and height to set the image to.
 /// </param>
 /// <param name="anchorPosition">
 /// The <see cref="AnchorPosition"/> to apply to resized image.
 /// </param>
 public ResizeLayer(Size size, AnchorPosition anchorPosition)
 {
     this.Size = size;
     this.AnchorPosition = anchorPosition;
     this.ResizeMode = ResizeMode.Pad;
     this.BackgroundColor = Color.Transparent;
 }
Beispiel #2
0
        private AnchorPositionMode GetAnchorPositionMode(AnchorPosition anchorPosition)
        {
            switch (anchorPosition)
            {
            case AnchorPosition.TopLeft:
                return(AnchorPositionMode.TopLeft);

            case AnchorPosition.TopCenter:
                return(AnchorPositionMode.Top);

            case AnchorPosition.TopRight:
                return(AnchorPositionMode.TopRight);

            case AnchorPosition.CenterLeft:
                return(AnchorPositionMode.Left);

            case AnchorPosition.Center:
                return(AnchorPositionMode.Center);

            case AnchorPosition.CenterRight:
                return(AnchorPositionMode.Right);

            case AnchorPosition.BottomLeft:
                return(AnchorPositionMode.BottomLeft);

            case AnchorPosition.BottomCenter:
                return(AnchorPositionMode.Bottom);

            case AnchorPosition.BottomRight:
                return(AnchorPositionMode.BottomRight);

            default:
                throw new ArgumentOutOfRangeException($"AnchorPosition {anchorPosition.ToString()} not supported.");
            }
        }
        private void _AdaptModel(AnchorPosition pos, Anchor anchor)
        {
            Destroy(model);
            GameObject pref = prefabFromPos(pos);

            model = Instantiate <GameObject>(pref, anchor.transform);
            switch (pos)
            {
            case AnchorPosition.APLOR:
                model.transform.localPosition   += new Vector3(2, -1, 1.5f);
                model.transform.localEulerAngles = new Vector3(109, 0, 0);
                break;

            case AnchorPosition.APRoutes:
                model.transform.localPosition   += new Vector3(1, -1, 1.5f);
                model.transform.localEulerAngles = new Vector3(109, 0, 0);
                break;

            case AnchorPosition.APStatus:
                model.transform.localPosition   += new Vector3(0, -1, 1.5f);
                model.transform.localEulerAngles = new Vector3(109, 0, 0);
                break;

            case AnchorPosition.APWall:
                model.transform.localPosition   += new Vector3(-1, -1, 1.5f);
                model.transform.localEulerAngles = new Vector3(109, 0, 0);
                break;

            default:
                break;
            }
        }
Beispiel #4
0
 private void GenerateUIs()
 {
     //Hardcoded because the corners in a ui are limited
     GenerateUI(AllCultures[0], AnchorPosition.LeftDownAnchor());
     GenerateUI(AllCultures[1], AnchorPosition.RightUpAnchor());
     GenerateUI(AllCultures[2], AnchorPosition.RightDownAnchor());
 }
Beispiel #5
0
        public static void CropImage(string pathFrom, string destinationPath, int Width, int Height,
                                     AnchorPosition anchor, ImageFormat format, CropOptions cropOptions)
        {
            string pathRead = pathFrom;

            if (pathFrom == destinationPath)
            {
                FileInfo fi = new FileInfo(pathFrom);
                pathRead = Path.Combine(fi.Directory.FullName, System.Guid.NewGuid().ToString() + Path.GetExtension(pathFrom));
                fi.MoveTo(pathRead);
            }

            System.Drawing.Image im   = System.Drawing.Image.FromFile(pathRead);
            System.Drawing.Image dest = Crop(im, Width, Height, cropOptions);

            if (format == ImageFormat.Jpeg)
            {
                SaveJpeg(destinationPath, dest, JpegQuality);
            }
            else
            {
                dest.Save(destinationPath, format);
            }

            im.Dispose();
            dest.Dispose();

            if (pathRead != pathFrom)
            {
                File.Delete(pathRead);
            }

            RotateImageByExifOrientationData(destinationPath, true);
        }
Beispiel #6
0
    private void UpdateCurrentPosition(AnchorPosition anchorPos)
    {
        string name        = anchorPos.SpatialAnchorObject.Name;
        string destination = destinationAnchor;

        updateMinimap(name.Substring(0, name.Length - 1), destination.Substring(0, destination.Length - 1));
    }
Beispiel #7
0
        public static AnchorElement AnchorElement(AnchorPosition position, NodeElement owner, Canvas canvas)
        {
            if (owner == null)
            {
                throw new ArgumentNullException(nameof(owner));
            }
            int x = 0, y = 0;

            switch (position)
            {
            case AnchorPosition.Top:
                x = owner.X + owner.Width / 2;
                y = owner.Y;
                break;

            case AnchorPosition.Right:
                x = owner.X + owner.Width;
                y = owner.Y + owner.Height / 2;
                break;

            case AnchorPosition.Bottom:
                x = owner.X + owner.Width / 2;
                y = owner.Y + owner.Height;
                break;

            case AnchorPosition.Left:
                x = owner.X;
                y = owner.Y + owner.Height / 2;
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(position), position, null);
            }
            return(new Anchor(x, y, owner, canvas));
        }
        private ThumbnailOption Create(JObject jObject)
        {
            ResizeMethod resultResizeMethod = default(ResizeMethod);
            var          resizeMethod       = jObject["method"];

            if (resizeMethod != null)
            {
                Enum.TryParse(resizeMethod.Value <string>(), out resultResizeMethod);
            }

            AnchorPosition resultAnchorPosition = default(AnchorPosition);
            var            anchorPosition       = jObject["anchorposition"];

            if (anchorPosition != null)
            {
                Enum.TryParse(anchorPosition.Value <string>(), out resultAnchorPosition);
            }

            var result = new ThumbnailOption()
            {
                BackgroundColor = jObject["color"]?.Value <string>(),
                FileSuffix      = jObject["alias"]?.Value <string>(),
                Width           = jObject["width"]?.Value <int>(),
                Height          = jObject["height"]?.Value <int>(),
                AnchorPosition  = resultAnchorPosition,
                ResizeMethod    = resultResizeMethod
            };

            return(result);
        }
 public byte[] Get(string relativeFilePath, int width, int height, ImageMod imageMod, string hexBackgroundColour, AnchorPosition? anchor, OutputFormat outputFormat)
 {
     using (var bitmap = Get(relativeFilePath, width, height, imageMod, hexBackgroundColour, anchor))
     {
         return bitmap.GetBytes(outputFormat);
     }
 }
    private Vector2 getOrigo(AnchorPosition anchor, Rect viewport)
    {
        Vector2 origo = new Vector2();

        switch (anchor)
        {
        case AnchorPosition.BOTTOM_LEFT:
            origo.y = Screen.height - viewport.height;
            break;

        case AnchorPosition.BOTTOM_RIGHT:
            origo.x = Screen.width - viewport.width;
            origo.y = Screen.height - viewport.height;
            break;

        case AnchorPosition.TOP_LEFT:
            //Do nothing..
            break;

        case AnchorPosition.TOP_RIGHT:
            origo.x = Screen.width - viewport.width;
            break;
        }
        return(origo);
    }
Beispiel #11
0
 public SubwindowSpec(AnchorPosition anchor, float x, float y)
 {
     Anchor    = anchor;
     Position  = new Vector2(x, y);
     xRelative = false;
     yRelative = false;
 }
Beispiel #12
0
    private void GenerateTransitionLines()
    {
        LinkedListNode <string> it = anchorList.First;

        while (it != anchorList.Last)
        {
            AnchorPosition baseAnchor   = null;
            AnchorPosition targetAnchor = null;
            foreach (AnchorPosition anchorPos in SceneAnchorPositions)
            {
                if (anchorPos.SpatialAnchorObject.Name == it.Value)
                {
                    baseAnchor = anchorPos;
                }

                if (anchorPos.SpatialAnchorObject.Name == it.Next.Value)
                {
                    targetAnchor = anchorPos;
                }
            }

            if (baseAnchor != null && targetAnchor != null)
            {
                baseAnchor.ConnectToAnchor(targetAnchor);
            }
            else
            {
                Debug.Log($"Cannot find the anchor connecting to {it.Value}");
                break;
            }

            it = it.Next;
        }
    }
        private static Image Crop(Image imgPhoto, int Width, int Height, AnchorPosition Anchor)
        {
            int   num10;
            int   width  = imgPhoto.Width;
            int   height = imgPhoto.Height;
            int   x      = 0;
            int   y      = 0;
            int   num5   = 0;
            int   num6   = 0;
            float num7   = 0f;
            float num8   = 0f;
            float num9   = 0f;

            num8 = ((float)Width) / ((float)width);
            num9 = ((float)Height) / ((float)height);
            if (num9 >= num8)
            {
                num7 = num9;
                switch (Anchor)
                {
                case AnchorPosition.Left:
                    num5 = 0;
                    goto Label_00D1;

                case AnchorPosition.Right:
                    num5 = Width - ((int)(width * num7));
                    goto Label_00D1;
                }
                num5 = (int)((Width - (width * num7)) / 2f);
            }
            else
            {
                num7 = num8;
                switch (Anchor)
                {
                case AnchorPosition.Top:
                    num6 = 0;
                    goto Label_00D1;

                case AnchorPosition.Bottom:
                    num6 = Height - ((int)(height * num7));
                    goto Label_00D1;
                }
                num6 = (int)((Height - (height * num7)) / 2f);
            }
Label_00D1:
            num10 = (int)(width * num7);
            int    num11 = (int)(height * num7);
            Bitmap image = new Bitmap(Width - 1, Height - 1, PixelFormat.Format24bppRgb);

            image.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);
            Graphics graphics = Graphics.FromImage(image);

            graphics.Clear(Color.White);
            graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
            graphics.DrawImage(imgPhoto, new Rectangle(num5, num6, num10, num11), new Rectangle(x, y, width, height - 2), GraphicsUnit.Pixel);
            graphics.Dispose();
            return(image);
        }
Beispiel #14
0
 public void CancelAnchorProfile()
 {
     // remove the instance of AnchorPosition
     Destroy(currentAnchorPosition.gameObject);
     // assign previousSpatialAnchor to currentSpatialAnchor
     currentAnchorPosition  = previousAnchorPosition;
     previousAnchorPosition = SceneAnchorPositions[SceneAnchorPositions.Count - 1];
 }
 public FANBannerData(AdSize adSize, AdPosition adPosition, float xPos, float yPos, AnchorPosition anchorPos = AnchorPosition.Center)
 {
     this.adSize         = adSize;
     this.adPosition     = adPosition;
     this.xPos           = xPos;
     this.yPos           = yPos;
     this.anchorPosition = anchorPos;
 }
Beispiel #16
0
            protected override bool OnMouseMove(MouseMoveEvent e)
            {
                var angle = AnchorPosition.GetDegreesFromPosition(e.MousePosition);

                Rotation = angle;

                return(base.OnMouseMove(e));
            }
Beispiel #17
0
 public Bitmap Get(string relativeFilePath, int width, int height, ImageMod imageMod, string hexBackgroundColour, AnchorPosition? anchor)
 {
     using (var image = (relativeFilePath == "Default"
         ? getDefault(width, height)
         : loadImage(relativeFilePath) ?? getDefault(width, height)))
     {
         return ResizeUtility.Get(image, width, height, imageMod, hexBackgroundColour, anchor);
     }
 }
Beispiel #18
0
    static void RenderMapGizmono(AnchorPosition map, GizmoType gizmoType)
    {
        var p = map.transform.position;

        Handles.color = Gizmos.color = map.color;
        Gizmos.DrawSphere(p, map.transform.localScale.magnitude * 0.2f);
        Handles.color = Gizmos.color = new Color(1, 1, 1, 1);
        Handles.Label(p, map.name);
    }
Beispiel #19
0
    private void UpdateCurrentPosition(AnchorPosition anchorPos)
    {
        //Debug.Log(anchorPos.SpatialAnchorObject.Name);
        //Debug.Log("******Call Proximity " + name.Substring(3,name.Length-3) + " CurrentanchorID " + currentAnchorID);
        string name        = anchorPos.SpatialAnchorObject.Name;
        string destination = destinationAnchor;

        updateMinimap(name.Substring(0, name.Length - 1), destination.Substring(0, destination.Length - 1));
    }
Beispiel #20
0
    public void ConnectToAnchor(AnchorPosition target)
    {
        var lineDataProvider = GetComponent <SimpleLineDataProvider>();

        lineDataProvider.EndPoint = new MixedRealityPose(target.GetTransform().position, Quaternion.identity);
        var mrLineRenderer = GetComponent <MixedRealityLineRenderer>();

        mrLineRenderer.enabled = true;
    }
Beispiel #21
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="text">Text to display</param>
        /// <param name="color">Color of the text</param>
        /// <param name="fontSize">Size of the text's characters</param>
        /// <param name="anchor">Position of the text's anchor</param>
        public TextDebugDrawer(string text, Color color, float fontSize, AnchorPosition anchor = AnchorPosition.TopLeft)
        {
            Color      = color;
            m_fontSize = fontSize;

            m_textLines      = text.Split(s_newlineCharacters, StringSplitOptions.RemoveEmptyEntries);
            m_anchorPosition = new Vector2(GetHorizontalAnchorOffset(m_textLines, anchor) * fontSize,
                                           GetVerticalAnchorOffset(m_textLines, anchor) * fontSize);
        }
Beispiel #22
0
    public void ConnectToAnchor(AnchorPosition target)
    {
        var lineDataProvider = GetComponent <SimpleLineDataProvider>();

        lineDataProvider.SetPoint(1, target.GetTransform().position);
        var mrLineRenderer = GetComponent <MixedRealityLineRenderer>();

        mrLineRenderer.enabled = true;
    }
Beispiel #23
0
        public override void Read(EndianStream stream)
        {
            base.Read(stream);

            AnchorMin.Read(stream);
            AnchorMax.Read(stream);
            AnchorPosition.Read(stream);
            SizeDelta.Read(stream);
            Pivot.Read(stream);
        }
Beispiel #24
0
        public override void Read(AssetReader reader)
        {
            base.Read(reader);

            AnchorMin.Read(reader);
            AnchorMax.Read(reader);
            AnchorPosition.Read(reader);
            SizeDelta.Read(reader);
            Pivot.Read(reader);
        }
Beispiel #25
0
        /// <summary>
        /// Resizes the image to a certain width and height. It will crop the image whenever necessary. The module will not perform
        /// any image resizing if both width and height are set to <c>null</c>. If the source image is smaller than the specified
        /// width and height, the image will be enlarged.
        /// </summary>
        /// <param name="width">The desired width. If set to <c>null</c> or <c>0</c>, the image will be resized to its height.</param>
        /// <param name="height">The desired height. If set to <c>null</c> or <c>0</c>, the image will be resized to its width.</param>
        /// <param name="anchor">The anchor position to use for cropping (if necessary). The available values are:
        /// <list type="bullet">
        /// <item><description>AnchorPosition.Center</description></item>
        /// <item><description>AnchorPosition.Top</description></item>
        /// <item><description>AnchorPosition.Bottom</description></item>
        /// <item><description>AnchorPosition.Left</description></item>
        /// <item><description>AnchorPosition.Right</description></item>
        /// <item><description>AnchorPosition.TopLeft</description></item>
        /// <item><description>AnchorPosition.TopRight</description></item>
        /// <item><description>AnchorPosition.BottomLeft</description></item>
        /// <item><description>AnchorPosition.BottomRight</description></item>
        /// </list>
        /// </param>
        public Image Resize(int?width, int?height, AnchorPosition anchor = AnchorPosition.Center)
        {
            EnsureCurrentInstruction();

            _currentInstruction.Width          = width;
            _currentInstruction.Height         = height;
            _currentInstruction.AnchorPosition = anchor;

            return(this);
        }
Beispiel #26
0
        protected override YAMLMappingNode ExportYAMLRoot(IExportContainer container)
        {
            YAMLMappingNode node = base.ExportYAMLRoot(container);

            node.Add("m_AnchorMin", AnchorMin.ExportYAML(container));
            node.Add("m_AnchorMax", AnchorMax.ExportYAML(container));
            node.Add("m_AnchoredPosition", AnchorPosition.ExportYAML(container));
            node.Add("m_SizeDelta", SizeDelta.ExportYAML(container));
            node.Add("m_Pivot", Pivot.ExportYAML(container));
            return(node);
        }
Beispiel #27
0
    private Vector2 AnchorToVector(AnchorPosition anchorPosition)
    {
        Vector2 result = new Vector2(0, 0);

        result.x += (anchorPosition & AnchorPosition.Right) > 0 ? 1 : 0;
        result.x += (anchorPosition & AnchorPosition.Left) > 0 ? -1 : 0;
        result.y += (anchorPosition & AnchorPosition.Top) > 0 ? 1 : 0;
        result.y += (anchorPosition & AnchorPosition.Bottom) > 0 ? -1 : 0;

        return(result);
    }
Beispiel #28
0
        protected override YAMLMappingNode ExportYAMLRoot(IExportContainer container)
        {
            YAMLMappingNode node = base.ExportYAMLRoot(container);

            node.Add(AnchorMinName, AnchorMin.ExportYAML(container));
            node.Add(AnchorMaxName, AnchorMax.ExportYAML(container));
            node.Add(AnchoredPositionName, AnchorPosition.ExportYAML(container));
            node.Add(SizeDeltaName, SizeDelta.ExportYAML(container));
            node.Add(PivotName, Pivot.ExportYAML(container));
            return(node);
        }
Beispiel #29
0
 public static Bitmap Get(Image image, int width, int height, ImageMod imageMod, string hexBackgroundColour, AnchorPosition? anchor)
 {
     switch (imageMod)
     {
         case ImageMod.Scale:
             return Scale(image, width, height, hexBackgroundColour);
         case ImageMod.Crop:
             return Crop(image, width, height, anchor ?? AnchorPosition.Center);
         default:
             return Scale(image, width, height, hexBackgroundColour);
     }
 }
        private void _TrackingMarker(AugmentedImage image)
        {
            AnchorPosition pos = _PosForName(image.Name);
            Anchor         anchor;

            if (!anchors.TryGetValue(pos, out anchor))
            {
                anchor = image.CreateAnchor(image.CenterPose);
                anchors.Add(pos, anchor);
                _AdaptModel(pos, anchor);
            }
        }
Beispiel #31
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ResizeLayer"/> class.
 /// </summary>
 /// <param name="size">
 /// The <see cref="T:System.Drawing.Size"/> containing the width and height to set the image to.
 /// </param>
 /// <param name="backgroundColor">
 /// The <see cref="T:System.Drawing.Color"/> to set as the background color.
 /// <remarks>Used for image formats that do not support transparency (Default transparent)</remarks>
 /// </param>
 /// <param name="resizeMode">
 /// The resize mode to apply to resized image. (Default ResizeMode.Pad)
 /// </param>
 /// <param name="anchorPosition">
 /// The <see cref="AnchorPosition"/> to apply to resized image. (Default AnchorPosition.Center)
 /// </param>
 /// <param name="upscale">
 /// Whether to allow up-scaling of images. (Default true)
 /// </param>
 public ResizeLayer(
     Size size,
     Color? backgroundColor = null,
     ResizeMode resizeMode = ResizeMode.Pad,
     AnchorPosition anchorPosition = AnchorPosition.Center,
     bool upscale = true)
 {
     this.Size = size;
     this.Upscale = upscale;
     this.BackgroundColor = backgroundColor ?? Color.Transparent;
     this.ResizeMode = resizeMode;
     this.AnchorPosition = anchorPosition;
 }
Beispiel #32
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ResizeLayer"/> class.
 /// </summary>
 /// <param name="size">
 /// The <see cref="T:System.Drawing.Size"/> containing the width and height to set the image to.
 /// </param>
 /// <param name="backgroundColor">
 /// The <see cref="T:System.Drawing.Color"/> to set as the background color.
 /// <remarks>Used for image formats that do not support transparency (Default transparent)</remarks>
 /// </param>
 /// <param name="resizeMode">
 /// The resize mode to apply to resized image. (Default ResizeMode.Pad)
 /// </param>
 /// <param name="anchorPosition">
 /// The <see cref="AnchorPosition"/> to apply to resized image. (Default AnchorPosition.Center)
 /// </param>
 /// <param name="upscale">
 /// Whether to allow up-scaling of images. (Default true)
 /// </param>
 public ResizeLayer(
     Size size,
     Color?backgroundColor         = null,
     ResizeMode resizeMode         = ResizeMode.Stretch,
     AnchorPosition anchorPosition = AnchorPosition.Center,
     bool upscale = true)
 {
     this.Size            = size;
     this.Upscale         = upscale;
     this.BackgroundColor = backgroundColor ?? Color.Transparent;
     this.ResizeMode      = resizeMode;
     this.AnchorPosition  = anchorPosition;
 }
Beispiel #33
0
        /// <summary>
        /// Resize and trim excess.
        /// The image will have given size
        /// </summary>
        public virtual Image Crop(Image image, int width, int height, AnchorPosition anchor)
        {
            var source = new ImageDimensions {
                Width = image.Width, Height = image.Height
            };
            var destination = new ImageDimensions();

            float nPercent;
            var   nPercentW = width / (float)source.Width;
            var   nPercentH = height / (float)source.Height;

            if (nPercentH < nPercentW)
            {
                nPercent = nPercentW;
                if (anchor == AnchorPosition.TopLeft || anchor == AnchorPosition.TopCenter || anchor == AnchorPosition.TopRight)
                {
                    destination.Y = 0;
                }
                else if (anchor == AnchorPosition.BottomLeft || anchor == AnchorPosition.BottomCenter || anchor == AnchorPosition.BottomRight)
                {
                    destination.Y = (int)(height - source.Height * nPercent);
                }
                else
                {
                    destination.Y = (int)((height - source.Height * nPercent) / 2);
                }
            }
            else
            {
                nPercent = nPercentH;
                if (anchor == AnchorPosition.TopLeft || anchor == AnchorPosition.CenterLeft || anchor == AnchorPosition.BottomLeft)
                {
                    destination.X = 0;
                }
                else if (anchor == AnchorPosition.TopRight || anchor == AnchorPosition.CenterRight || anchor == AnchorPosition.BottomRight)
                {
                    destination.X = (int)(width - source.Width * nPercent);
                }
                else
                {
                    destination.X = (int)((width - source.Width * nPercent) / 2);
                }
            }

            destination.Width  = (int)(source.Width * nPercent);
            destination.Height = (int)(source.Height * nPercent);

            return(Transform(image, source, destination, new Size {
                Height = height, Width = width
            }, null));
        }
Beispiel #34
0
    public void ShowTooltip(string message, Rectangle target, AnchorPosition anchor, float duration)
    {
        if (this.currentTween != null)
        {
            this.currentTween.Kill();
        }

        this.gameObject.SetActive(true);

        this.duration   = duration;
        this.label.text = message;
        this.label.ComputeMarginSize();

        float width = this.label.GetPreferredValues().x + 2 * this.labelMargin;

        this.back.Width = width;
        float height = this.back.Height;

        float targetWidth  = target.Width;
        float targetHeight = target.Height;

        DOTween.To((float t) =>
        {
            this.backColorHidden.a = t;
            this.back.Color        = this.backColorHidden;
        },
                   0.0f,
                   1.0f,
                   this.transitionDuration);

        this.label.DOColor(this.labelColorVisible, this.transitionDuration);

        Vector2 deltaDirection = this.AnchorToVector(anchor);
        Vector3 position       = target.transform.position;

        position.x       += deltaDirection.x * targetWidth * .5f + width * .5f * deltaDirection.x;
        position.y       += deltaDirection.y * targetHeight * .5f + height * .5f * deltaDirection.y;
        this.hidePosition = position;
        position         += new Vector3(deltaDirection.x, deltaDirection.y, 0) * this.targetMargin;

        this.transform.position = this.hidePosition;
        this.currentTween       = this.transform.DOMove(position, this.transitionDuration).SetEase(Ease.OutCubic).OnKill(() =>
        {
            this.currentTween = null;
            this.currentState = State.Visible;
        });

        this.showDate     = UnityEngine.Time.timeSinceLevelLoad;
        this.currentState = State.TransitionToVisible;
    }
Beispiel #35
0
        /// <summary>
        /// Resizes the given image.
        /// </summary>
        /// <param name="source">The source <see cref="Image"/> to resize.</param>
        /// <param name="linear">Whether to resize the image using the linear color space.</param>
        /// <returns>
        /// The resized <see cref="Image"/>.
        /// </returns>
        public Bitmap ResizeImage(Image source, bool linear)
        {
            int            width   = this.ResizeLayer.Size.Width;
            int            height  = this.ResizeLayer.Size.Height;
            ResizeMode     mode    = this.ResizeLayer.ResizeMode;
            AnchorPosition anchor  = this.ResizeLayer.AnchorPosition;
            bool           upscale = this.ResizeLayer.Upscale;

            float[]     centerCoordinates = this.ResizeLayer.CenterCoordinates;
            int         maxWidth          = this.ResizeLayer.MaxSize.HasValue ? this.ResizeLayer.MaxSize.Value.Width : int.MaxValue;
            int         maxHeight         = this.ResizeLayer.MaxSize.HasValue ? this.ResizeLayer.MaxSize.Value.Height : int.MaxValue;
            List <Size> restrictedSizes   = this.ResizeLayer.RestrictedSizes;

            return(this.ResizeImage(source, width, height, maxWidth, maxHeight, restrictedSizes, mode, anchor, upscale, centerCoordinates, linear));
        }
Beispiel #36
0
 public Bitmap Get(string relativeFilePath, int width, int height, ImageMod imageMod, string hexBackgroundColour, AnchorPosition? anchor)
 {
     using (var image = (relativeFilePath == "Default" ? getDefault(width, height) : loadImage(relativeFilePath) ?? getDefault(width, height)))
     {
         switch (imageMod)
         {
             case ImageMod.Scale:
                 return scale(image, width, height, hexBackgroundColour);
             case ImageMod.Crop:
                 return crop(image, width, height, anchor ?? AnchorPosition.Center);
             default:
                 return scale(image, width, height, hexBackgroundColour);
         }
     }
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="ResizeLayer"/> class.
 /// </summary>
 /// <param name="size">
 /// The <see cref="T:System.Drawing.Size"/> containing the width and height to set the image to.
 /// </param>
 /// <param name="resizeMode">
 /// The resize mode to apply to resized image. (Default ResizeMode.Pad)
 /// </param>
 /// <param name="anchorPosition">
 /// The <see cref="AnchorPosition"/> to apply to resized image. (Default AnchorPosition.Center)
 /// </param>
 /// <param name="upscale">
 /// Whether to allow up-scaling of images. (Default true)
 /// </param>
 /// <param name="centerCoordinates">
 /// The center coordinates (Default null)
 /// </param>
 /// <param name="maxSize">
 /// The maximum size to resize an image to. 
 /// Used to restrict resizing based on calculated resizing
 /// </param>
 /// <param name="restrictedSizes">
 /// The range of sizes to restrict resizing an image to. 
 /// Used to restrict resizing based on calculated resizing
 /// </param>
 public ResizeLayer(
     Size size,
     ResizeMode resizeMode = ResizeMode.Pad,
     AnchorPosition anchorPosition = AnchorPosition.Center,
     bool upscale = true,
     float[] centerCoordinates = null,
     Size? maxSize = null,
     List<Size> restrictedSizes = null)
 {
     this.Size = size;
     this.Upscale = upscale;
     this.ResizeMode = resizeMode;
     this.AnchorPosition = anchorPosition;
     this.CenterCoordinates = centerCoordinates ?? new float[] { };
     this.MaxSize = maxSize;
     this.RestrictedSizes = restrictedSizes ?? new List<Size>();
 }
Beispiel #38
0
	/// <summary>
	/// Funnctions that repositions the anchor based the postion chosen from the enum, through the screen to world point function.
	/// </summary>
	void RepositionAnchor()
	{
		// If the previous postion of the anchor is equal to the current position of the anchor, return out of the function.
		if (oldPosition == anchorPosition)
			return;
		if (!hudCamera)
			hudCamera = transform.parent.camera;

		float aspectRatio = (float)Screen.width / (float)Screen.height;
		float height = hudCamera.orthographicSize;
		float width = height * aspectRatio;

		switch (anchorPosition)
		{
		case AnchorPosition.TopLeft:
			transform.localPosition = (Vector3.left * width) + (Vector3.up * height);
			break;
		case AnchorPosition.Top:
			transform.localPosition = (Vector3.up * height);
			break;
		case AnchorPosition.TopRight:
			transform.localPosition = (Vector3.right * width) + (Vector3.up * height);
			break;
		case AnchorPosition.Left:
			transform.localPosition = (Vector3.left * width);
			break;
		case AnchorPosition.Center:
			transform.localPosition = Vector3.zero;
			break;
		case AnchorPosition.Right:
			transform.localPosition = (Vector3.right * width);
			break;
		case AnchorPosition.BottomLeft:
			transform.localPosition = (Vector3.left * width) + (Vector3.down * height);
			break;
		case AnchorPosition.Bottom:
			transform.localPosition = (Vector3.down * height);
			break;
		case AnchorPosition.BottomRight:
			transform.localPosition = (Vector3.right * width) + (Vector3.down * height);
			break;			
		default:
			break;		
		}
		// Set the name of the object to Anchor and what ever the anchor postion is.
		name = "Anchor - " + anchorPosition.ToString();
		// Then set old postion to the new position.
		oldPosition = anchorPosition;
	}
        public static Image Crop(Image image, int width, int height, AnchorPosition anchor)
        {
            int sourceWidth = image.Width;
            int sourceHeight = image.Height;
            int destX = 0;
            int destY = 0;

            float percent = 0;
            float percentWidth = 0;
            float percentHeight = 0;

            percentWidth = ((float)width / (float)sourceWidth);
            percentHeight = ((float)height / (float)sourceHeight);

            if (percentHeight < percentWidth)
            {
                percent = percentWidth;
                switch (anchor)
                {
                    case AnchorPosition.Top:
                        destY = 0;
                        break;
                    case AnchorPosition.Bottom:
                        destY = (int)(height - (sourceHeight * percent));
                        break;
                    default:
                        destY = (int)((height - (sourceHeight * percent)) / 2);
                        break;
                }
            }
            else
            {
                percent = percentHeight;
                switch (anchor)
                {
                    case AnchorPosition.Left:
                        destX = 0;
                        break;
                    case AnchorPosition.Right:
                        destX = (int)(width - (sourceWidth * percent));
                        break;
                    default:
                        destX = (int)((width - (sourceWidth * percent)) / 2);
                        break;
                }
            }

            int destWidth = (int)(sourceWidth * percent);
            int destHeight = (int)(sourceHeight * percent);

            Size size = new Size(destWidth, destHeight);

            Bitmap scaledImage = new Bitmap(width, height);
            scaledImage.SetResolution(image.HorizontalResolution, image.VerticalResolution);

            Graphics g = Graphics.FromImage(scaledImage);
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            g.PixelOffsetMode = PixelOffsetMode.HighQuality;
            g.CompositingQuality = CompositingQuality.HighQuality;
            g.SmoothingMode = SmoothingMode.HighQuality;

            g.DrawImage(image,
                new Rectangle(new Point(destX, destY), size),
                new Rectangle(new Point(0, 0), image.Size),
                GraphicsUnit.Pixel);
            g.Dispose();

            return scaledImage;
        }
 /// <summary>
 /// Funnctions that repositions the anchor based the postion chosen from the enum, through the screen to world point function.
 /// </summary>
 void RepositionAnchor()
 {
     // If the previous postion of the anchor is equal to the current position of the anchor, return out of the function.
     if (oldPosition == anchorPosition)
         return;
     if (!hudCamera)
         hudCamera = transform.parent.camera;
     switch (anchorPosition)
     {
     case AnchorPosition.TopLeft:
         transform.position = hudCamera.ScreenToWorldPoint(new Vector3(0, Screen.height, 0));
         break;
     case AnchorPosition.Top:
         transform.position = hudCamera.ScreenToWorldPoint(new Vector3(Screen.width / 2, Screen.height, 0));
         break;
     case AnchorPosition.TopRight:
         transform.position = hudCamera.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height, 0));
         break;
     case AnchorPosition.Left:
         transform.position = hudCamera.ScreenToWorldPoint(new Vector3(0, Screen.height / 2, 0));
         break;
     case AnchorPosition.Center:
         transform.position = hudCamera.ScreenToWorldPoint(new Vector3(Screen.width / 2, Screen.height / 2, 0));
         break;
     case AnchorPosition.Right:
         transform.position = hudCamera.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height / 2, 0));
         break;
     case AnchorPosition.BottomLeft:
         transform.position = hudCamera.ScreenToWorldPoint(new Vector3(0, 0, 0));
         break;
     case AnchorPosition.Bottom:
         transform.position = hudCamera.ScreenToWorldPoint(new Vector3(Screen.width / 2, 0, 0));
         break;
     case AnchorPosition.BottomRight:
         transform.position = hudCamera.ScreenToWorldPoint(new Vector3(Screen.width, 0, 0));
         break;
     default:
         break;
     }
     // Set the name of the object to Anchor and what ever the anchor postion is.
     name = "Anchor - " + anchorPosition.ToString();
     // Then set old postion to the new position.
     oldPosition = anchorPosition;
 }
        public static Image ImageCrop(Image image, int width, int height, AnchorPosition anchor)
        {
            int sourceWidth = image.Width;
            int sourceHeight = image.Height;
            int sourceX = 0;
            int sourceY = 0;
            int destX = 0;
            int destY = 0;

            float nPercent = 0;
            float nPercentW = 0;
            float nPercentH = 0;

            nPercentW = (Convert.ToSingle(width) / Convert.ToSingle(sourceWidth));
            nPercentH = (Convert.ToSingle(height) / Convert.ToSingle(sourceHeight));

            if (nPercentH < nPercentW)
            {
                nPercent = nPercentW;
                switch (anchor)
                {
                    case AnchorPosition.Top:
                        destY = 0;
                        break;
                    case AnchorPosition.Bottom:
                        destY = Convert.ToInt32(height - (sourceHeight * nPercent));
                        break;
                    default:
                        destY = Convert.ToInt32((height - (sourceHeight * nPercent)) / 2);
                        break;
                }
            }
            else
            {
                nPercent = nPercentH;
                switch (anchor)
                {
                    case AnchorPosition.Left:
                        destX = 0;
                        break;
                    case AnchorPosition.Right:
                        destX = Convert.ToInt32((width - (sourceWidth * nPercent)));
                        break;
                    default:
                        destX = Convert.ToInt32(((width - (sourceWidth * nPercent)) / 2));
                        break;
                }
            }

            int destWidth = Convert.ToInt32((sourceWidth * nPercent));
            int destHeight = Convert.ToInt32((sourceHeight * nPercent));

            Bitmap bmPhoto = new Bitmap(width, height, PixelFormat.Format24bppRgb);
            bmPhoto.SetResolution(image.HorizontalResolution, image.VerticalResolution);

            Graphics grPhoto = Graphics.FromImage(bmPhoto);
            grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;
            grPhoto.DrawImage(image, new Rectangle(destX, destY, destWidth, destHeight), new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight), GraphicsUnit.Pixel);
            grPhoto.Dispose();

            return bmPhoto;
        }
Beispiel #42
0
        /// <summary>
        /// The resize image.
        /// </summary>
        /// <param name="factory">
        /// The the current instance of the <see cref="T:ImageProcessor.ImageFactory"/> class containing
        /// the image to process.
        /// </param>
        /// <param name="width">
        /// The width to resize the image to.
        /// </param>
        /// <param name="height">
        /// The height to resize the image to.
        /// </param>
        /// <param name="defaultMaxWidth">
        /// The default max width to resize the image to.
        /// </param>
        /// <param name="defaultMaxHeight">
        /// The default max height to resize the image to.
        /// </param>
        /// <param name="backgroundColor">
        /// The background color to pad the image with.
        /// </param>
        /// <param name="resizeMode">
        /// The mode with which to resize the image.
        /// </param>
        /// <param name="anchorPosition">
        /// The anchor position to place the image at.
        /// </param>
        /// <param name="upscale">
        /// Whether to allow up-scaling of images. (Default true)
        /// </param>
        /// <returns>
        /// The processed image from the current instance of the <see cref="T:ImageProcessor.ImageFactory"/> class.
        /// </returns>
        private Image ResizeImage(
            ImageFactory factory,
            int width,
            int height,
            int defaultMaxWidth,
            int defaultMaxHeight,
            Color backgroundColor,
            ResizeMode resizeMode = ResizeMode.Pad,
            AnchorPosition anchorPosition = AnchorPosition.Center,
            bool upscale = true)
        {
            Bitmap newImage = null;
            Image image = factory.Image;

            try
            {
                int sourceWidth = image.Width;
                int sourceHeight = image.Height;

                int destinationWidth = width;
                int destinationHeight = height;

                int maxWidth = defaultMaxWidth > 0 ? defaultMaxWidth : int.MaxValue;
                int maxHeight = defaultMaxHeight > 0 ? defaultMaxHeight : int.MaxValue;

                // Fractional variants for preserving aspect ratio.
                double percentHeight = Math.Abs(height / (double)sourceHeight);
                double percentWidth = Math.Abs(width / (double)sourceWidth);

                int destinationX = 0;
                int destinationY = 0;

                // Change the destination rectangle coordinates if padding and
                // there has been a set width and height.
                if (resizeMode == ResizeMode.Pad && width > 0 && height > 0)
                {
                    double ratio;

                    if (percentHeight < percentWidth)
                    {
                        ratio = percentHeight;
                        destinationX = (int)((width - (sourceWidth * ratio)) / 2);
                        destinationWidth = (int)Math.Ceiling(sourceWidth * percentHeight);
                    }
                    else
                    {
                        ratio = percentWidth;
                        destinationY = (int)((height - (sourceHeight * ratio)) / 2);
                        destinationHeight = (int)Math.Ceiling(sourceHeight * percentWidth);
                    }
                }

                // Change the destination rectangle coordinates if cropping and
                // there has been a set width and height.
                if (resizeMode == ResizeMode.Crop && width > 0 && height > 0)
                {
                    double ratio;

                    if (percentHeight < percentWidth)
                    {
                        ratio = percentWidth;

                        switch (anchorPosition)
                        {
                            case AnchorPosition.Top:
                                destinationY = 0;
                                break;
                            case AnchorPosition.Bottom:
                                destinationY = (int)(height - (sourceHeight * ratio));
                                break;
                            default:
                                destinationY = (int)((height - (sourceHeight * ratio)) / 2);
                                break;
                        }

                        destinationHeight = (int)Math.Ceiling(sourceHeight * percentWidth);
                    }
                    else
                    {
                        ratio = percentHeight;

                        switch (anchorPosition)
                        {
                            case AnchorPosition.Left:
                                destinationX = 0;
                                break;
                            case AnchorPosition.Right:
                                destinationX = (int)(width - (sourceWidth * ratio));
                                break;
                            default:
                                destinationX = (int)((width - (sourceWidth * ratio)) / 2);
                                break;
                        }

                        destinationWidth = (int)Math.Ceiling(sourceWidth * percentHeight);
                    }
                }

                // Constrain the image to fit the maximum possible height or width.
                if (resizeMode == ResizeMode.Max)
                {
                    if (sourceWidth > width || sourceHeight > height)
                    {
                        double ratio = Math.Abs(height / width);
                        double sourceRatio = Math.Abs(sourceHeight / sourceWidth);

                        if (sourceRatio < ratio)
                        {
                            height = 0;
                        }
                        else
                        {
                            width = 0;
                        }
                    }
                }

                // If height or width is not passed we assume that the standard ratio is to be kept.
                if (height == 0)
                {
                    destinationHeight = (int)Math.Ceiling(sourceHeight * percentWidth);
                    height = destinationHeight;
                }

                if (width == 0)
                {
                    destinationWidth = (int)Math.Ceiling(sourceWidth * percentHeight);
                    width = destinationWidth;
                }

                if (width > 0 && height > 0 && width <= maxWidth && height <= maxHeight)
                {
                    // Exit if upscaling is not allowed.
                    if ((width > sourceWidth || height > sourceHeight) && upscale == false && resizeMode != ResizeMode.Stretch)
                    {
                        return image;
                    }

                    newImage = new Bitmap(width, height, PixelFormat.Format32bppPArgb);

                    using (Graphics graphics = Graphics.FromImage(newImage))
                    {
                        // We want to use two different blending algorithms for enlargement/shrinking.
                        // Bicubic is better enlarging for whilst Bilinear is better for shrinking.
                        // http://www.codinghorror.com/blog/2007/07/better-image-resizing.html
                        if (image.Width < destinationWidth && image.Height < destinationHeight)
                        {
                            // We are making it larger.
                            graphics.SmoothingMode = SmoothingMode.AntiAlias;
                            graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                            graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
                            graphics.CompositingQuality = CompositingQuality.HighQuality;
                        }
                        else
                        {
                            // We are making it smaller.
                            graphics.SmoothingMode = SmoothingMode.None;
                            graphics.InterpolationMode = InterpolationMode.HighQualityBilinear;
                            graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
                            graphics.CompositingQuality = CompositingQuality.HighQuality;
                        }

                        // An unwanted border appears when using InterpolationMode.HighQualityBicubic to resize the image
                        // as the algorithm appears to be pulling averaging detail from surCeilinging pixels beyond the edge
                        // of the image. Using the ImageAttributes class to specify that the pixels beyond are simply mirror
                        // images of the pixels within solves this problem.
                        using (ImageAttributes wrapMode = new ImageAttributes())
                        {
                            wrapMode.SetWrapMode(WrapMode.TileFlipXY);
                            graphics.Clear(backgroundColor);
                            Rectangle destRect = new Rectangle(destinationX, destinationY, destinationWidth, destinationHeight);
                            graphics.DrawImage(image, destRect, 0, 0, sourceWidth, sourceHeight, GraphicsUnit.Pixel, wrapMode);
                        }

                        // Reassign the image.
                        image.Dispose();
                        image = newImage;
                    }
                }
            }
            catch
            {
                if (newImage != null)
                {
                    newImage.Dispose();
                }
            }

            return image;
        }
Beispiel #43
0
        /// <summary>
        /// Resizes the given image.
        /// </summary>
        /// <param name="source">
        /// The source <see cref="Image"/> to resize
        /// </param>
        /// <param name="width">
        /// The width to resize the image to.
        /// </param>
        /// <param name="height">
        /// The height to resize the image to.
        /// </param>
        /// <param name="maxWidth">
        /// The default max width to resize the image to.
        /// </param>
        /// <param name="maxHeight">
        /// The default max height to resize the image to.
        /// </param>
        /// <param name="restrictedSizes">
        /// A <see cref="List{T}"/> containing image resizing restrictions.
        /// </param>
        /// <param name="resizeMode">
        /// The mode with which to resize the image.
        /// </param>
        /// <param name="anchorPosition">
        /// The anchor position to place the image at.
        /// </param>
        /// <param name="upscale">
        /// Whether to allow up-scaling of images. (Default true)
        /// </param>
        /// <param name="centerCoordinates">
        /// If the resize mode is crop, you can set a specific center coordinate, use as alternative to anchorPosition
        /// </param>
        /// <returns>
        /// The resized <see cref="Image"/>.
        /// </returns>
        private Bitmap ResizeImage(
            Image source,
            int width,
            int height,
            int maxWidth,
            int maxHeight,
            List<Size> restrictedSizes,
            ResizeMode resizeMode = ResizeMode.Pad,
            AnchorPosition anchorPosition = AnchorPosition.Center,
            bool upscale = true,
            float[] centerCoordinates = null)
        {
            Bitmap newImage = null;

            try
            {
                int sourceWidth = source.Width;
                int sourceHeight = source.Height;

                int destinationWidth = width;
                int destinationHeight = height;

                maxWidth = maxWidth > 0 ? maxWidth : int.MaxValue;
                maxHeight = maxHeight > 0 ? maxHeight : int.MaxValue;

                // Fractional variants for preserving aspect ratio.
                double percentHeight = Math.Abs(height / (double)sourceHeight);
                double percentWidth = Math.Abs(width / (double)sourceWidth);

                int destinationX = 0;
                int destinationY = 0;

                // Change the destination rectangle coordinates if padding and
                // there has been a set width and height.
                if (resizeMode == ResizeMode.Pad && width > 0 && height > 0)
                {
                    double ratio;

                    if (percentHeight < percentWidth)
                    {
                        ratio = percentHeight;
                        destinationWidth = Convert.ToInt32(sourceWidth * percentHeight);

                        switch (anchorPosition)
                        {
                            case AnchorPosition.Left:
                                destinationX = 0;
                                break;
                            case AnchorPosition.Right:
                                destinationX = (int)(width - (sourceWidth * ratio));
                                break;
                            default:
                                destinationX = Convert.ToInt32((width - (sourceWidth * ratio)) / 2);
                                break;
                        }
                    }
                    else
                    {
                        ratio = percentWidth;
                        destinationHeight = Convert.ToInt32(sourceHeight * percentWidth);

                        switch (anchorPosition)
                        {
                            case AnchorPosition.Top:
                                destinationY = 0;
                                break;
                            case AnchorPosition.Bottom:
                                destinationY = (int)(height - (sourceHeight * ratio));
                                break;
                            default:
                                destinationY = (int)((height - (sourceHeight * ratio)) / 2);
                                break;
                        }
                    }
                }

                // Change the destination rectangle coordinates if cropping and
                // there has been a set width and height.
                if (resizeMode == ResizeMode.Crop && width > 0 && height > 0)
                {
                    double ratio;

                    if (percentHeight < percentWidth)
                    {
                        ratio = percentWidth;

                        if (centerCoordinates != null && centerCoordinates.Any())
                        {
                            double center = -(ratio * sourceHeight) * centerCoordinates[0];
                            destinationY = (int)center + (height / 2);

                            if (destinationY > 0)
                            {
                                destinationY = 0;
                            }

                            if (destinationY < (int)(height - (sourceHeight * ratio)))
                            {
                                destinationY = (int)(height - (sourceHeight * ratio));
                            }
                        }
                        else
                        {
                            switch (anchorPosition)
                            {
                                case AnchorPosition.Top:
                                    destinationY = 0;
                                    break;
                                case AnchorPosition.Bottom:
                                    destinationY = (int)(height - (sourceHeight * ratio));
                                    break;
                                default:
                                    destinationY = (int)((height - (sourceHeight * ratio)) / 2);
                                    break;
                            }
                        }

                        destinationHeight = (int)Math.Ceiling(sourceHeight * percentWidth);
                    }
                    else
                    {
                        ratio = percentHeight;

                        if (centerCoordinates != null && centerCoordinates.Any())
                        {
                            double center = -(ratio * sourceWidth) * centerCoordinates[1];
                            destinationX = (int)center + (width / 2);

                            if (destinationX > 0)
                            {
                                destinationX = 0;
                            }

                            if (destinationX < (int)(width - (sourceWidth * ratio)))
                            {
                                destinationX = (int)(width - (sourceWidth * ratio));
                            }
                        }
                        else
                        {
                            switch (anchorPosition)
                            {
                                case AnchorPosition.Left:
                                    destinationX = 0;
                                    break;
                                case AnchorPosition.Right:
                                    destinationX = (int)(width - (sourceWidth * ratio));
                                    break;
                                default:
                                    destinationX = (int)((width - (sourceWidth * ratio)) / 2);
                                    break;
                            }
                        }

                        destinationWidth = (int)Math.Ceiling(sourceWidth * percentHeight);
                    }
                }

                // Constrain the image to fit the maximum possible height or width.
                if (resizeMode == ResizeMode.Max)
                {
                    // If either is 0, we don't need to figure out orientation
                    if (width > 0 && height > 0)
                    {
                        // Integers must be cast to doubles to get needed precision
                        double ratio = (double)height / width;
                        double sourceRatio = (double)sourceHeight / sourceWidth;

                        if (sourceRatio < ratio)
                        {
                            height = 0;
                        }
                        else
                        {
                            width = 0;
                        }
                    }
                }

                // If height or width is not passed we assume that the standard ratio is to be kept.
                if (height == 0)
                {
                    destinationHeight = Convert.ToInt32(sourceHeight * percentWidth);
                    height = destinationHeight;
                }

                if (width == 0)
                {
                    destinationWidth = Convert.ToInt32(sourceWidth * percentHeight);
                    width = destinationWidth;
                }

                // Restrict sizes
                if (restrictedSizes != null && restrictedSizes.Any())
                {
                    bool reject = true;
                    foreach (Size restrictedSize in restrictedSizes)
                    {
                        if (restrictedSize.Height == 0 || restrictedSize.Width == 0)
                        {
                            if (restrictedSize.Width == width || restrictedSize.Height == height)
                            {
                                reject = false;
                            }
                        }
                        else if (restrictedSize.Width == width && restrictedSize.Height == height)
                        {
                            reject = false;
                        }
                    }

                    if (reject)
                    {
                        return (Bitmap)source;
                    }
                }

                if (width > 0 && height > 0 && width <= maxWidth && height <= maxHeight)
                {
                    // Exit if upscaling is not allowed.
                    if ((width > sourceWidth || height > sourceHeight) && upscale == false && resizeMode != ResizeMode.Stretch)
                    {
                        return (Bitmap)source;
                    }

                    newImage = new Bitmap(width, height);
                    newImage.SetResolution(source.HorizontalResolution, source.VerticalResolution);

                    using (Graphics graphics = Graphics.FromImage(newImage))
                    {
                        // We want to use two different blending algorithms for enlargement/shrinking.
                        if (source.Width < destinationWidth && source.Height < destinationHeight)
                        {
                            // We are making it larger.
                            graphics.SmoothingMode = SmoothingMode.AntiAlias;
                        }
                        else
                        {
                            // We are making it smaller.
                            graphics.SmoothingMode = SmoothingMode.None;
                        }

                        graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                        graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
                        graphics.CompositingQuality = CompositingQuality.HighQuality;

                        // An unwanted border appears when using InterpolationMode.HighQualityBicubic to resize the image
                        // as the algorithm appears to be pulling averaging detail from surrounding pixels beyond the edge
                        // of the image. Using the ImageAttributes class to specify that the pixels beyond are simply mirror
                        // images of the pixels within solves this problem.
                        using (ImageAttributes wrapMode = new ImageAttributes())
                        {
                            wrapMode.SetWrapMode(WrapMode.TileFlipXY);
                            Rectangle destinationRectangle = new Rectangle(destinationX, destinationY, destinationWidth, destinationHeight);
                            graphics.DrawImage(source, destinationRectangle, 0, 0, sourceWidth, sourceHeight, GraphicsUnit.Pixel, wrapMode);
                        }

                        // Reassign the image.
                        source.Dispose();
                        source = newImage;
                    }
                }
            }
            catch (Exception ex)
            {
                if (newImage != null)
                {
                    newImage.Dispose();
                }

                throw new ImageProcessingException("Error processing image with " + this.GetType().Name, ex);
            }

            return (Bitmap)source;
        }
Beispiel #44
0
        public static Image Crop(Image imgPhoto, int Width,
					int Height, AnchorPosition Anchor)
        {
            int sourceWidth = imgPhoto.Width;
            int sourceHeight = imgPhoto.Height;
            int sourceX = 0;
            int sourceY = 0;
            int destX = 0;
            int destY = 0;

            float nPercent = 0;
            float nPercentW = 0;
            float nPercentH = 0;

            nPercentW = ((float)Width / (float)sourceWidth);
            nPercentH = ((float)Height / (float)sourceHeight);

            if(nPercentH < nPercentW)
            {
                nPercent = nPercentW;
                switch(Anchor)
                {
                    case AnchorPosition.Top:
                        destY = 0;
                        break;
                    case AnchorPosition.Bottom:
                        destY = (int)
                            (Height - (sourceHeight * nPercent));
                        break;
                    default:
                        destY = (int)
                            ((Height - (sourceHeight * nPercent)) / 2);
                        break;
                }
            }
            else
            {
                nPercent = nPercentH;
                switch(Anchor)
                {
                    case AnchorPosition.Left:
                        destX = 0;
                        break;
                    case AnchorPosition.Right:
                        destX = (int)
                          (Width - (sourceWidth * nPercent));
                        break;
                    default:
                        destX = (int)
                          ((Width - (sourceWidth * nPercent)) / 2);
                        break;
                }
            }

            int destWidth = (int)(sourceWidth * nPercent);
            int destHeight = (int)(sourceHeight * nPercent);

            Bitmap bmPhoto = new Bitmap(Width,
                    Height, PixelFormat.Format24bppRgb);
            bmPhoto.SetResolution(imgPhoto.HorizontalResolution,
                    imgPhoto.VerticalResolution);

            Graphics grPhoto = Graphics.FromImage(bmPhoto);
            grPhoto.InterpolationMode =
                    InterpolationMode.HighQualityBicubic;

            grPhoto.DrawImage(imgPhoto,
                new Rectangle(destX, destY, destWidth, destHeight),
                new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight),
                GraphicsUnit.Pixel);

            grPhoto.Dispose();
            return bmPhoto;
        }
        public static Image Crop(Image img, int width, int height, AnchorPosition Anchor)
        {
            if (img == null) return null;

            int sourceWidth = img.Width;
            int sourceHeight = img.Height;
            int sourceX = 0;
            int sourceY = 0;
            int destX = 0;
            int destY = 0;

            float nPercent = 0;
            float nPercentW = 0;
            float nPercentH = 0;

            nPercentW = ((float)width / (float)sourceWidth);
            nPercentH = ((float)height / (float)sourceHeight);

            if (nPercentH < nPercentW)
            {
                nPercent = nPercentW;
                switch (Anchor)
                {
                    case AnchorPosition.Top:
                        destY = 0;
                        break;
                    case AnchorPosition.Bottom:
                        destY = (int)(height - (sourceHeight * nPercent));
                        break;
                    default:
                        destY = (int)((height - (sourceHeight * nPercent)) / 2);
                        break;
                }
            }
            else
            {
                nPercent = nPercentH;
                switch (Anchor)
                {
                    case AnchorPosition.Left:
                        destX = 0;
                        break;
                    case AnchorPosition.Right:
                        destX = (int)(width - (sourceWidth * nPercent));
                        break;
                    default:
                        destX = (int)((width - (sourceWidth * nPercent)) / 2);
                        break;
                }
            }

            int destWidth = (int)(sourceWidth * nPercent);
            int destHeight = (int)(sourceHeight * nPercent);

            Bitmap bmPhoto = new Bitmap(width, height, PixelFormat.Format24bppRgb);
            bmPhoto.SetResolution(img.HorizontalResolution, img.VerticalResolution);

            Graphics grPhoto = Graphics.FromImage(bmPhoto);
            grPhoto.Clear(Color.White);
            //grPhoto.SmoothingMode = SmoothingMode.AntiAlias;
            grPhoto.SmoothingMode = SmoothingMode.HighSpeed;
            grPhoto.CompositingQuality = CompositingQuality.HighQuality;
            grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;
            //grPhoto.TextRenderingHint = TextRenderingHint.AntiAlias;

            Rectangle destRec = new Rectangle(destX, destY, destWidth, destHeight);
            Rectangle sourceRec = new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight);

            grPhoto.DrawImage(img,
                              destRec,
                              sourceRec,
                              GraphicsUnit.Pixel);

            grPhoto.Dispose();

            //Quantizer
            //OctreeQuantizer quantizer = new OctreeQuantizer(255, 8);
            //bmPhoto = quantizer.Quantize(bmPhoto);

            return bmPhoto;
        }
Beispiel #46
0
 public static System.Drawing.Image ImageCrop(string imgURL, int Width, int Height, AnchorPosition Anchor)
 {
     try
     {
         Bitmap b;
         //try
         //{
             WebClient wc = new WebClient();
             byte[] img = wc.DownloadData(imgURL);
             MemoryStream imgStream = new MemoryStream(img);
             b = (Bitmap)System.Drawing.Image.FromStream(imgStream);
         //}
         //catch (Exception ex1)
         //{
             //b = (Bitmap)System.Drawing.Image.FromFile(HttpContext.Current.Server.MapPath(imgURL.Replace("http://", "")));
         //}
         return ImageCrop(b, Width, Height, Anchor);
     }
     catch (Exception ex) { }
     Bitmap bm = new Bitmap(Width, Height);
     Graphics g = Graphics.FromImage(bm);
     g.FillRectangle(new SolidBrush(Color.Black), 0, 0, (float)Width, (float)Height);
     g.Dispose();
     return bm;
 }
Beispiel #47
0
        private Bitmap crop(Image image, int width, int height, AnchorPosition Anchor)
        {
            var sourceWidth = image.Width;
            var sourceHeight = image.Height;
            var sourceX = 0;
            var sourceY = 0;
            var destX = 0;
            var destY = 0;

            float nPercent;
            float nPercentW;
            float nPercentH;

            nPercentW = (width / (float)sourceWidth);
            nPercentH = (height / (float)sourceHeight);

            if (nPercentH < nPercentW)
            {
                nPercent = nPercentW;
                switch (Anchor)
                {
                    case AnchorPosition.Top:
                        destY = 0;
                        break;
                    case AnchorPosition.Bottom:
                        destY = (int)(height - Math.Round(sourceHeight * nPercent));
                        break;
                    default:
                        destY = (int)((height - Math.Round(sourceHeight * nPercent)) / 2);
                        break;
                }
            }
            else
            {
                nPercent = nPercentH;
                switch (Anchor)
                {
                    case AnchorPosition.Left:
                        destX = 0;
                        break;
                    case AnchorPosition.Right:
                        destX = (int)(width - Math.Round(sourceWidth * nPercent));
                        break;
                    default:
                        destX = (int)((width - Math.Round(sourceWidth * nPercent)) / 2);
                        break;
                }
            }

            var destWidth = (int)Math.Round(sourceWidth * nPercent);
            var destHeight = (int)Math.Round(sourceHeight * nPercent);

            var bmPhoto = new Bitmap(width, height, PixelFormat.Format24bppRgb);
            bmPhoto.SetResolution(image.HorizontalResolution, image.VerticalResolution);

            var grPhoto = Graphics.FromImage(bmPhoto);

            grPhoto.Clear(Utilities.BackgroundColour);
            grPhoto.PixelOffsetMode = PixelOffsetMode.HighQuality;
            grPhoto.CompositingQuality = CompositingQuality.HighQuality;
            grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;
            grPhoto.CompositingMode = CompositingMode.SourceCopy;

            var imageAttributes = new ImageAttributes();
            imageAttributes.SetWrapMode(WrapMode.TileFlipXY);

            grPhoto.DrawImage(image,
                new Rectangle(destX, destY, destWidth, destHeight),
                sourceX, sourceY, sourceWidth, sourceHeight,
                GraphicsUnit.Pixel, imageAttributes);

            grPhoto.Dispose();
            return bmPhoto;
        }
Beispiel #48
0
 public byte[] GetCached(string relativeFilePath, int width, int height, ImageMod imageMod, string hexBackgroundColour, AnchorPosition? anchor, OutputFormat outputFormat)
 {
     var key = string.Format("ImageManager-{0}-{1}-{2}-{3}-{4}", relativeFilePath, width, height, imageMod, outputFormat);
     if (Context.Cache[key] == null)
     {
         var image = Get(relativeFilePath, width, height, imageMod, hexBackgroundColour, anchor, outputFormat);
         if (image == null) throw new FileNotFoundException("The image requested does not exist.");
         Context.Cache.Insert(key, image, null, Cache.NoAbsoluteExpiration, Configs.CacheExpiration);
     }
     return (byte[])Context.Cache[key];
 }
Beispiel #49
0
        public Image Crop(Image imgPhoto, int Width, int Height, AnchorPosition Anchor)
        {
            int sourceWidth = imgPhoto.Width;
            int sourceHeight = imgPhoto.Height;
            int sourceX = 0;
            int sourceY = 0;
            int destX = 0;
            int destY = 0;

            float nPercent = 0;
            float nPercentW = 0;
            float nPercentH = 0;

            nPercentW = ((float)Width / (float)sourceWidth);
            nPercentH = ((float)Height / (float)sourceHeight);

            if (nPercentH < nPercentW)
            {
                nPercent = nPercentW;
                switch (Anchor)
                {
                    case AnchorPosition.Top:
                        destY = 0;
                        break;
                    case AnchorPosition.Bottom:
                        destY = (int)(Height - (sourceHeight * nPercent));
                        break;
                    default:
                        destY = (int)((Height - (sourceHeight * nPercent)) / 3);
                        break;
                }
            }
            else
            {
                nPercent = nPercentH;
                switch (Anchor)
                {
                    case AnchorPosition.Left:
                        destX = 0;
                        break;
                    case AnchorPosition.Right:
                        destX = (int)(Width - (sourceWidth * nPercent));
                        break;
                    default:
                        destX = (int)((Width - (sourceWidth * nPercent)) / 2);
                        break;
                }
            }

            int destWidth = (int)(sourceWidth * nPercent);
            int destHeight = (int)(sourceHeight * nPercent);

            Bitmap bmPhoto = new Bitmap(Width, Height, PixelFormat.Format32bppArgb);
            bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);

            Graphics grPhoto = Graphics.FromImage(bmPhoto);
            //grPhoto.Clear(Color.White);
            grPhoto.SmoothingMode = SmoothingMode.HighQuality;
            grPhoto.InterpolationMode = InterpolationMode.HighQualityBilinear;
            grPhoto.CompositingQuality = CompositingQuality.HighQuality;
            grPhoto.PixelOffsetMode = PixelOffsetMode.HighQuality;

            grPhoto.DrawImage(imgPhoto,
                new Rectangle(destX - 2, destY - 2, destWidth + 4, destHeight + 4),
                new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight),
                GraphicsUnit.Pixel);

            grPhoto.Dispose();

            //OnSharpen
            //if (Width < 168)
            //{
            //    BitmapFilter.Sharpen(bmPhoto, 14);
            //}

            return bmPhoto;
        }
Beispiel #50
0
 public Stream Get(Stream file, int width, int height, ImageMod imageMod, string hexBackgroundColour, AnchorPosition? anchor, OutputFormat outputFormat)
 {
     return ResizeUtility.Get(loadImage(file) ?? getDefault(width, height), width, height, imageMod, hexBackgroundColour, anchor).GetStream(outputFormat);
 }
Beispiel #51
0
        /// <summary>
        /// Resizes the image to a certain width and height. It will crop the image whenever necessary. The module will not perform 
        /// any image resizing if both width and height are set to <c>null</c>. If the source image is smaller than the specified 
        /// width and height, the image will be enlarged.
        /// </summary>
        /// <param name="width">The desired width. If set to <c>null</c> or <c>0</c>, the image will be resized to its height.</param>
        /// <param name="height">The desired height. If set to <c>null</c> or <c>0</c>, the image will be resized to its width.</param>
        /// <param name="anchor">The anchor position to use for cropping (if necessary). The available values are:
        /// <list type="bullet"> 
        /// <item><description>AnchorPosition.Center</description></item>
        /// <item><description>AnchorPosition.Top</description></item>
        /// <item><description>AnchorPosition.Bottom</description></item>
        /// <item><description>AnchorPosition.Left</description></item>
        /// <item><description>AnchorPosition.Right</description></item>
        /// <item><description>AnchorPosition.TopLeft</description></item>
        /// <item><description>AnchorPosition.TopRight</description></item>
        /// <item><description>AnchorPosition.BottomLeft</description></item>
        /// <item><description>AnchorPosition.BottomRight</description></item>
        /// </list>
        /// </param>
        public Image Resize(int? width, int? height, AnchorPosition anchor = AnchorPosition.Center)
        {
            EnsureCurrentInstruction();

            _currentInstruction.Width = width;
            _currentInstruction.Height = height;
            _currentInstruction.AnchorPosition = anchor;

            return this;
        }
Beispiel #52
0
    protected Image Crop(Image imgPhoto, int Width,
                    int Height, AnchorPosition Anchor, int HorizontalRuler, int VerticalRuler,
      string Text, int TextHeight, int FontSize)
    {
        int sourceWidth = imgPhoto.Width;
        int sourceHeight = imgPhoto.Height;
        int sourceX = 0;
        int sourceY = 0;
        int destX = 0;
        int destY = 0;

        float nPercent = 0;
        float nPercentW = 0;
        float nPercentH = 0;

        nPercentW = ((float)Width / (float)sourceWidth);
        nPercentH = ((float)Height / (float)sourceHeight);

        sourceWidth = (nPercentW <= 0.25) ? (int)(sourceWidth * 0.75) : sourceWidth;
        sourceHeight = (nPercentH <= 0.25) ? (int)(sourceHeight * 0.75) : sourceHeight;

        nPercentW = ((float)Width / (float)sourceWidth);
        nPercentH = ((float)Height / (float)sourceHeight);

        if (nPercentW > 1)
        {
            nPercentW = 1;
            Width = sourceWidth;
        }

        if (nPercentH > 1)
        {
            nPercentH = 1;
            Height = sourceHeight;
        }

        if (nPercentH < nPercentW)
        {
            nPercent = nPercentW;

            if (nPercent != 1.0)
            {
                switch (Anchor)
                {
                    case AnchorPosition.Top:
                        destY = 0;
                        break;
                    case AnchorPosition.Bottom:
                        destY = (int)
                            (Height - (sourceHeight * nPercent));
                        break;
                    default:

                        destY = (int)
                        ((Height - (sourceHeight * nPercent)) / 2);

                        destX = -(int)
                          ((Width - (sourceWidth * nPercentH)) / 2);

                        break;
                }
            }
        }
        else
        {
            nPercent = nPercentH;

            if (nPercent != 1.0)
            {
                switch (Anchor)
                {
                    case AnchorPosition.Left:
                        destX = 0;
                        break;
                    case AnchorPosition.Right:
                        destX = (int)
                          (Width - (sourceWidth * nPercent));
                        break;
                    default:
                        destX = (int)
                     ((Width - (sourceWidth * nPercent)) / 2);

                        destY = -(int)
                           ((Height - (sourceHeight * nPercentW)) / 2);

                        break;
                }
            }
        }

        int destWidth = (int)(sourceWidth * nPercent);
        int destHeight = (int)(sourceHeight * nPercent);

        if (nPercent == nPercentW)
        {
            destWidth -= destX;
        }
        else
        {
            destHeight -= destY;
        }

        Bitmap bmPhoto = new Bitmap(Width,
                Height, PixelFormat.Format24bppRgb);
        bmPhoto.SetResolution(imgPhoto.HorizontalResolution,
                imgPhoto.VerticalResolution);

        Graphics grPhoto = Graphics.FromImage(bmPhoto);
        grPhoto.Clear(Color.White);
        grPhoto.InterpolationMode =
                InterpolationMode.HighQualityBicubic;

        grPhoto.DrawImage(imgPhoto,
            new Rectangle(destX, destY, destWidth, destHeight),
            new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight),
            GraphicsUnit.Pixel);

        Pen pen = new Pen(Color.White);
        pen.Width = 1.5F;

        grPhoto.DrawImage(imgPhoto,
            new Rectangle(destX, destY, destWidth, destHeight),
            new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight),
            GraphicsUnit.Pixel);

        if (Text.Length > 0)
        {
            StringFormat sf = new StringFormat();
            Font font = new Font("Arial", FontSize, FontStyle.Bold);
            Rectangle rect = new Rectangle();
            Color customColor = Color.FromArgb(140, Color.Black);
            SolidBrush brush = new SolidBrush(customColor);

            rect.X = 0;
            rect.Y = Height - TextHeight;
            rect.Width = Width;
            rect.Height = TextHeight;

            sf.LineAlignment = StringAlignment.Center;
            sf.Alignment = StringAlignment.Center;

            grPhoto.FillRectangle(brush, rect);
            grPhoto.DrawString("\"" + Text + "\"", font, Brushes.White, rect, sf);
        }

        if (VerticalRuler > 0)
            grPhoto.DrawLine(pen, Width / 2, 0, Width / 2, Height);

        if (HorizontalRuler > 0)
            grPhoto.DrawLine(pen, 0, Height / 2, Width, Height / 2);

        grPhoto.Dispose();
        return bmPhoto;
    }
Beispiel #53
0
        public static Image Crop(Image imgPhoto, int width, int height, AnchorPosition anchor)
        {
            int sourceWidth = imgPhoto.Width;
            int sourceHeight = imgPhoto.Height;
            const int sourceX = 0;
            const int sourceY = 0;
            int destX = -1;
            int destY = -1;
            double nPercent;
            double nPercentW = (width / (double)sourceWidth);
            double nPercentH = (height / (double)sourceHeight);

            if (nPercentH < nPercentW)
            {
                nPercent = nPercentW;
                switch (anchor)
                {
                    case AnchorPosition.Top:
                        destY = 0;
                        break;
                    case AnchorPosition.Bottom:
                        destY = (int)(height - (sourceHeight * nPercent));
                        break;
                    default:
                        destY = (int)((height - (sourceHeight * nPercent)) / 2);
                        break;
                }
            }
            else
            {
                nPercent = nPercentH;
                switch (anchor)
                {
                    case AnchorPosition.Left:
                        destX = 0;
                        break;
                    case AnchorPosition.Right:
                        destX = (int)(width - (sourceWidth * nPercent));
                        break;
                    default:
                        destX = (int)((width - (sourceWidth * nPercent)) / 2);
                        break;
                }
            }

            var destWidth = (int)(sourceWidth * nPercent);
            var destHeight = (int)(sourceHeight * nPercent);

            var bmPhoto = new Bitmap(width, height, PixelFormat.Format24bppRgb);
            bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);

            Graphics grPhoto = Graphics.FromImage(bmPhoto);
            grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;

            grPhoto.DrawImage(imgPhoto,
                              new Rectangle(destX, destY, destWidth + 2, destHeight + 2),
                              new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight),
                              GraphicsUnit.Pixel);

            grPhoto.Dispose();
            return bmPhoto;
        }
Beispiel #54
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ResizeLayer"/> class.
 /// </summary>
 /// <param name="backgroundColor">
 /// The <see cref="T:System.Drawing.Color"/> to set as the background color.
 /// <remarks>Used for image formats that do not support transparency</remarks>
 /// </param>
 /// <param name="resizeMode">
 /// The resize mode to apply to resized image.
 /// </param>
 /// <param name="anchorPosition">
 /// The <see cref="AnchorPosition"/> to apply to resized image.
 /// </param>
 public ResizeLayer(Color backgroundColor, ResizeMode resizeMode = ResizeMode.Pad, AnchorPosition anchorPosition = AnchorPosition.Center)
 {
     this.BackgroundColor = backgroundColor;
     this.ResizeMode = resizeMode;
     this.AnchorPosition = anchorPosition;
 }
Beispiel #55
0
        /// <summary>
        /// Resizes the given image.
        /// </summary>
        /// <param name="source">The source <see cref="Image"/> to resize</param>
        /// <param name="width">The width to resize the image to.</param>
        /// <param name="height">The height to resize the image to.</param>
        /// <param name="maxWidth">The default max width to resize the image to.</param>
        /// <param name="maxHeight">The default max height to resize the image to.</param>
        /// <param name="restrictedSizes">A <see cref="List{T}"/> containing image resizing restrictions.</param>
        /// <param name="resizeMode">The mode with which to resize the image.</param>
        /// <param name="anchorPosition">The anchor position to place the image at.</param>
        /// <param name="upscale">Whether to allow up-scaling of images. (Default true)</param>
        /// <param name="centerCoordinates">
        /// If the resize mode is crop, you can set a specific center coordinate, use as alternative to anchorPosition
        /// </param>
        /// <param name="linear">Whether to resize the image using the linear color space.</param>
        /// <returns>
        /// The resized <see cref="Image"/>.
        /// </returns>
        private Bitmap ResizeImage(
            Image source,
            int width,
            int height,
            int maxWidth,
            int maxHeight,
            List<Size> restrictedSizes,
            ResizeMode resizeMode = ResizeMode.Pad,
            AnchorPosition anchorPosition = AnchorPosition.Center,
            bool upscale = true,
            float[] centerCoordinates = null,
            bool linear = false)
        {
            Bitmap newImage = null;

            try
            {
                int sourceWidth = source.Width;
                int sourceHeight = source.Height;

                int destinationWidth = width;
                int destinationHeight = height;

                maxWidth = maxWidth > 0 ? maxWidth : int.MaxValue;
                maxHeight = maxHeight > 0 ? maxHeight : int.MaxValue;

                // Fractional variants for preserving aspect ratio.
                double percentHeight = Math.Abs(height / (double)sourceHeight);
                double percentWidth = Math.Abs(width / (double)sourceWidth);

                int destinationX = 0;
                int destinationY = 0;

                // Change the destination rectangle coordinates if box padding.
                if (resizeMode == ResizeMode.BoxPad)
                {
                    height = height > 0 ? height : Convert.ToInt32(sourceHeight * percentWidth);
                    width = width > 0 ? width : Convert.ToInt32(sourceWidth * percentHeight);

                    // Only calculate if upscaling. 
                    if (sourceWidth < width || sourceHeight < height)
                    {
                        destinationWidth = sourceWidth;
                        destinationHeight = sourceHeight;

                        upscale = true;

                        switch (anchorPosition)
                        {
                            case AnchorPosition.Left:
                                destinationY = (height - sourceHeight) / 2;
                                destinationX = 0;
                                break;
                            case AnchorPosition.Right:
                                destinationY = (height - sourceHeight) / 2;
                                destinationX = width - sourceWidth;
                                break;
                            case AnchorPosition.TopRight:
                                destinationY = 0;
                                destinationX = width - sourceWidth;
                                break;
                            case AnchorPosition.Top:
                                destinationY = 0;
                                destinationX = (width - sourceWidth) / 2;
                                break;
                            case AnchorPosition.TopLeft:
                                destinationY = 0;
                                destinationX = 0;
                                break;
                            case AnchorPosition.BottomRight:
                                destinationY = height - sourceHeight;
                                destinationX = width - sourceWidth;
                                break;
                            case AnchorPosition.Bottom:
                                destinationY = height - sourceHeight;
                                destinationX = (width - sourceWidth) / 2;
                                break;
                            case AnchorPosition.BottomLeft:
                                destinationY = height - sourceHeight;
                                destinationX = 0;
                                break;
                            default:
                                destinationY = (height - sourceHeight) / 2;
                                destinationX = (width - sourceWidth) / 2;
                                break;
                        }
                    }
                    else
                    {
                        // Switch to pad mode to downscale and calculate from there. 
                        resizeMode = ResizeMode.Pad;
                    }
                }

                // Change the destination rectangle coordinates if padding and
                // there has been a set width and height.
                if (resizeMode == ResizeMode.Pad && width > 0 && height > 0)
                {
                    double ratio;

                    if (percentHeight < percentWidth)
                    {
                        ratio = percentHeight;
                        destinationWidth = Convert.ToInt32(sourceWidth * percentHeight);

                        switch (anchorPosition)
                        {
                            case AnchorPosition.Left:
                            case AnchorPosition.TopLeft:
                            case AnchorPosition.BottomLeft:
                                destinationX = 0;
                                break;
                            case AnchorPosition.Right:
                            case AnchorPosition.TopRight:
                            case AnchorPosition.BottomRight:
                                destinationX = (int)(width - (sourceWidth * ratio));
                                break;
                            default:
                                destinationX = Convert.ToInt32((width - (sourceWidth * ratio)) / 2);
                                break;
                        }
                    }
                    else
                    {
                        ratio = percentWidth;
                        destinationHeight = Convert.ToInt32(sourceHeight * percentWidth);

                        switch (anchorPosition)
                        {
                            case AnchorPosition.Top:
                            case AnchorPosition.TopLeft:
                            case AnchorPosition.TopRight:
                                destinationY = 0;
                                break;
                            case AnchorPosition.Bottom:
                            case AnchorPosition.BottomLeft:
                            case AnchorPosition.BottomRight:
                                destinationY = (int)(height - (sourceHeight * ratio));
                                break;
                            default:
                                destinationY = (int)((height - (sourceHeight * ratio)) / 2);
                                break;
                        }
                    }
                }

                // Change the destination rectangle coordinates if cropping and
                // there has been a set width and height.
                if (resizeMode == ResizeMode.Crop && width > 0 && height > 0)
                {
                    double ratio;

                    if (percentHeight < percentWidth)
                    {
                        ratio = percentWidth;

                        if (centerCoordinates != null && centerCoordinates.Any())
                        {
                            double center = -(ratio * sourceHeight) * centerCoordinates[0];
                            destinationY = (int)center + (height / 2);

                            if (destinationY > 0)
                            {
                                destinationY = 0;
                            }

                            if (destinationY < (int)(height - (sourceHeight * ratio)))
                            {
                                destinationY = (int)(height - (sourceHeight * ratio));
                            }
                        }
                        else
                        {
                            switch (anchorPosition)
                            {
                                case AnchorPosition.Top:
                                case AnchorPosition.TopLeft:
                                case AnchorPosition.TopRight:
                                    destinationY = 0;
                                    break;
                                case AnchorPosition.Bottom:
                                case AnchorPosition.BottomLeft:
                                case AnchorPosition.BottomRight:
                                    destinationY = (int)(height - (sourceHeight * ratio));
                                    break;
                                default:
                                    destinationY = (int)((height - (sourceHeight * ratio)) / 2);
                                    break;
                            }
                        }

                        destinationHeight = (int)Math.Ceiling(sourceHeight * percentWidth);
                    }
                    else
                    {
                        ratio = percentHeight;

                        if (centerCoordinates != null && centerCoordinates.Any())
                        {
                            double center = -(ratio * sourceWidth) * centerCoordinates[1];
                            destinationX = (int)center + (width / 2);

                            if (destinationX > 0)
                            {
                                destinationX = 0;
                            }

                            if (destinationX < (int)(width - (sourceWidth * ratio)))
                            {
                                destinationX = (int)(width - (sourceWidth * ratio));
                            }
                        }
                        else
                        {
                            switch (anchorPosition)
                            {
                                case AnchorPosition.Left:
                                case AnchorPosition.TopLeft:
                                case AnchorPosition.BottomLeft:
                                    destinationX = 0;
                                    break;
                                case AnchorPosition.Right:
                                case AnchorPosition.TopRight:
                                case AnchorPosition.BottomRight:
                                    destinationX = (int)(width - (sourceWidth * ratio));
                                    break;
                                default:
                                    destinationX = (int)((width - (sourceWidth * ratio)) / 2);
                                    break;
                            }
                        }

                        destinationWidth = (int)Math.Ceiling(sourceWidth * percentHeight);
                    }
                }

                // Constrain the image to fit the maximum possible height or width.
                if (resizeMode == ResizeMode.Max)
                {
                    // If either is 0, we don't need to figure out orientation
                    if (width > 0 && height > 0)
                    {
                        // Integers must be cast to doubles to get needed precision
                        double ratio = (double)height / width;
                        double sourceRatio = (double)sourceHeight / sourceWidth;

                        if (sourceRatio < ratio)
                        {
                            height = 0;
                        }
                        else
                        {
                            width = 0;
                        }
                    }
                }

                // Resize the image until the shortest side reaches the set given dimension.
                if (resizeMode == ResizeMode.Min)
                {
                    height = height > 0 ? height : Convert.ToInt32(sourceHeight * percentWidth);
                    width = width > 0 ? width : Convert.ToInt32(sourceWidth * percentHeight);

                    double sourceRatio = (double)sourceHeight / sourceWidth;

                    // Ensure we can't upscale.
                    maxHeight = sourceHeight;
                    maxWidth = sourceWidth;
                    upscale = false;

                    // Find the shortest distance to go.
                    int widthDiff = sourceWidth - width;
                    int heightDiff = sourceHeight - height;

                    if (widthDiff < heightDiff)
                    {
                        destinationHeight = Convert.ToInt32(width * sourceRatio);
                        height = destinationHeight;
                        destinationWidth = width;
                    }
                    else if (widthDiff > heightDiff)
                    {
                        destinationHeight = height;
                        destinationWidth = Convert.ToInt32(height / sourceRatio);
                        width = destinationWidth;
                    }
                    else
                    {
                        destinationWidth = width;
                        destinationHeight = height;
                    }
                }

                // If height or width is not passed we assume that the standard ratio is to be kept.
                if (height == 0)
                {
                    destinationHeight = Convert.ToInt32(sourceHeight * percentWidth);
                    height = destinationHeight;
                }

                if (width == 0)
                {
                    destinationWidth = Convert.ToInt32(sourceWidth * percentHeight);
                    width = destinationWidth;
                }

                // Restrict sizes
                if (restrictedSizes != null && restrictedSizes.Any())
                {
                    bool reject = true;
                    foreach (Size restrictedSize in restrictedSizes)
                    {
                        if (restrictedSize.Height == 0 || restrictedSize.Width == 0)
                        {
                            if (restrictedSize.Width == width || restrictedSize.Height == height)
                            {
                                reject = false;
                            }
                        }
                        else if (restrictedSize.Width == width && restrictedSize.Height == height)
                        {
                            reject = false;
                        }
                    }

                    if (reject)
                    {
                        return (Bitmap)source;
                    }
                }

                if (width > 0 && height > 0 && width <= maxWidth && height <= maxHeight)
                {
                    // Exit if upscaling is not allowed.
                    if ((width > sourceWidth || height > sourceHeight) && upscale == false && resizeMode != ResizeMode.Stretch)
                    {
                        return (Bitmap)source;
                    }

                    // Do the resize.
                    Rectangle destination = new Rectangle(destinationX, destinationY, destinationWidth, destinationHeight);

                    //if (this.ImageFormat is GifFormat || (this.ImageFormat is PngFormat && !((PngFormat)this.ImageFormat).IsIndexed))
                    //{
                    //    newImage = FastResizer.ResizeBilinear((Bitmap)source, width, height, destination, linear);
                    //}
                    //else
                    //{
                    //    if (width <= sourceWidth && height <= sourceHeight)
                    //    {
                    //        newImage = FastResizer.ResizeBicubicHighQuality((Bitmap)source, width, height, destination, linear);
                    //    }
                    //    else
                    //    {
                    //        // Faster
                    //        newImage = FastResizer.ResizeBilinear((Bitmap)source, width, height, destination, linear);
                    //    }
                    //}

                    newImage = linear ? ResizeLinear(source, width, height, destination) : ResizeComposite(source, width, height, destination);

                    // Reassign the image.
                    source.Dispose();
                    source = newImage;
                }
            }
            catch (Exception ex)
            {
                if (newImage != null)
                {
                    newImage.Dispose();
                }

                throw new ImageProcessingException("Error processing image with " + this.GetType().Name, ex);
            }

            return (Bitmap)source;
        }
Beispiel #56
0
 public static System.Drawing.Image ImageCropLocal(string imgURL, int Width, int Height, AnchorPosition Anchor)
 {
     try
     {
         Bitmap b;
         b = (Bitmap)System.Drawing.Image.FromFile(HttpContext.Current.Server.MapPath(imgURL));
         return ImageCrop(b, Width, Height, Anchor);
     }
     catch (Exception ex) { }
     Bitmap bm = new Bitmap(Width, Height);
     Graphics g = Graphics.FromImage(bm);
     g.FillRectangle(new SolidBrush(Color.Black), 0, 0, (float)Width, (float)Height);
     g.Dispose();
     return bm;
 }
Beispiel #57
0
        public static Image Crop(Image imgPhoto, int Width, int Height, AnchorPosition Anchor)
        {
            int sourceWidth = imgPhoto.Width;
            int sourceHeight = imgPhoto.Height;
            int sourceX = 0;
            int sourceY = 0;
            int destX = 0;
            int destY = 0;

            float nPercent = 0;
            float nPercentW = 0;
            float nPercentH = 0;

            nPercentW = ((float)Width / (float)sourceWidth);
            nPercentH = ((float)Height / (float)sourceHeight);

            if (nPercentH < nPercentW)
            {
                nPercent = nPercentW;
                switch (Anchor)
                {
                    case AnchorPosition.Top:
                        destY = 0;
                        break;
                    case AnchorPosition.Bottom:
                        destY = (int)(Height - (sourceHeight * nPercent));
                        break;
                    default:
                        destY = (int)((Height - (sourceHeight * nPercent)) / 2);
                        break;
                }
            }
            else
            {
                nPercent = nPercentH;
                switch (Anchor)
                {
                    case AnchorPosition.Left:
                        destX = 0;
                        break;
                    case AnchorPosition.Right:
                        destX = (int)(Width - (sourceWidth * nPercent));
                        break;
                    default:
                        destX = (int)((Width - (sourceWidth * nPercent)) / 2);
                        break;
                }
            }

            int destWidth = (int)(sourceWidth * nPercent);
            int destHeight = (int)(sourceHeight * nPercent);

            Bitmap bmPhoto = new Bitmap(Width, Height);
            bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);

            //Graphics grPhoto = Graphics.FromImage(bmPhoto);
            //grPhoto.InterpolationMode = InterpolationMode.High;

            //grPhoto.FillRectangle(Brushes.White, destX, destY, destWidth, destHeight); // Phuong add this line on 26/05/2008 to fix border issue

            //grPhoto.DrawImage(imgPhoto,
            //  new Rectangle(destX, destY, destWidth, destHeight),
            //  new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight),
            //  GraphicsUnit.Pixel);

            //grPhoto.Dispose();

            using (Graphics g = Graphics.FromImage(bmPhoto))
            {
                g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                g.FillRectangle(Brushes.White, destX, destY, destWidth, destHeight);
                g.DrawImage(imgPhoto,
                    new Rectangle(destX, destY, destWidth, destHeight),
                    new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight),
                    GraphicsUnit.Pixel);
            }

            return bmPhoto;
        }