How to resize an Image C#

前端 未结 17 2394
暗喜
暗喜 2020-11-21 22:28

As Size, Width and Height are Get() properties of System.Drawing.Image;
How can I resize an Image object

17条回答
  •  爱一瞬间的悲伤
    2020-11-21 23:19

    This will -

    • Resize width AND height without the need for a loop
    • Doesn't exceed the images original dimensions

    //////////////

    private void ResizeImage(Image img, double maxWidth, double maxHeight)
    {
        double resizeWidth = img.Source.Width;
        double resizeHeight = img.Source.Height;
    
        double aspect = resizeWidth / resizeHeight;
    
        if (resizeWidth > maxWidth)
        {
            resizeWidth = maxWidth;
            resizeHeight = resizeWidth / aspect;
        }
        if (resizeHeight > maxHeight)
        {
            aspect = resizeWidth / resizeHeight;
            resizeHeight = maxHeight;
            resizeWidth = resizeHeight * aspect;
        }
    
        img.Width = resizeWidth;
        img.Height = resizeHeight;
    }
    

提交回复
热议问题