C# crop image from center

前端 未结 6 1696
我寻月下人不归
我寻月下人不归 2020-12-09 13:48

I am developing application using .NET(4.5) MVC(4.0) C#(5.0). i want to generate image thumbnail from image that i already have. Now requirement is like it should generate t

6条回答
  •  攒了一身酷
    2020-12-09 14:47

    You need to get the ratio of the destination size against the actual size. Scale the shorter side until it touches the actual image size. Crop it starting from the center and scale it to the desired size.

    Here is the code:

    
    
     public static Image ResizeImage(Image imgToResize, Size destinationSize)
            {
                var originalWidth = imgToResize.Width;
                var originalHeight = imgToResize.Height;
    
                //how many units are there to make the original length
                var hRatio = (float)originalHeight/destinationSize.Height;
                var wRatio = (float)originalWidth/destinationSize.Width;
    
                //get the shorter side
                var ratio = Math.Min(hRatio, wRatio);
    
                var hScale = Convert.ToInt32(destinationSize.Height * ratio);
                var wScale = Convert.ToInt32(destinationSize.Width * ratio);
    
                //start cropping from the center
                var startX = (originalWidth - wScale)/2;
                var startY = (originalHeight - hScale)/2;
    
                //crop the image from the specified location and size
                var sourceRectangle = new Rectangle(startX, startY, wScale, hScale);
    
                //the future size of the image
                var bitmap = new Bitmap(destinationSize.Width, destinationSize.Height);
    
                //fill-in the whole bitmap
                var destinationRectangle = new Rectangle(0, 0, bitmap.Width, bitmap.Height);
    
                //generate the new image
                using (var g = Graphics.FromImage(bitmap))
                {
                    g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    g.DrawImage(imgToResize, destinationRectangle, sourceRectangle, GraphicsUnit.Pixel);
                }
    
                return bitmap;
    
            }
    
    
    

    Call it like this:

    
    var thumbImage = ImageHelper.ResizeImage(image, new Size(45, 45));
    thumbImage.Save(thumbFullPath);
    
    

提交回复
热议问题