Resizing image proportionally in ASP.NET C# by specifying either Height or Width

后端 未结 5 743
一整个雨季
一整个雨季 2021-02-11 07:33

I need a code that will allow me to resize images, but with the following functionality:

1) resize image upon upload

2) Resize image proportionally by specifying

5条回答
  •  有刺的猬
    2021-02-11 08:11

    Taken from this Stackoverflow answer, I come up with:

    public static Image Resize(this Image image, int maxWidth = 0, int maxHeight = 0)
        {
            if (maxWidth == 0)
                maxWidth = image.Width;
            if (maxHeight == 0)
                maxHeight = image.Height;
    
            var ratioX = (double)maxWidth / image.Width;
            var ratioY = (double)maxHeight / image.Height;
            var ratio = Math.Min(ratioX, ratioY);
    
            var newWidth = (int)(image.Width * ratio);
            var newHeight = (int)(image.Height * ratio);
    
            var newImage = new Bitmap(newWidth, newHeight);
            Graphics.FromImage(newImage).DrawImage(image, 0, 0, newWidth, newHeight);
            return newImage;
        }
    

    To resize Image specifying its maxWidth:

    var _image = Image.FromStream(Source);
    var _thumbImage = _image.Resize(100);
    

    To resize Image specifying its maxHeight:

    var _image = Image.FromStream(Source);
    var _thumbImage = _image.Resize(maxHeight: 100);
    

提交回复
热议问题