C# crop image from center

前端 未结 6 1702
我寻月下人不归
我寻月下人不归 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:43

    public Image ScaleImage(Image image, int maxWidth, int maxHeight)
    {
        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(maxWidth, maxWidth);
        using (var graphics = Graphics.FromImage(newImage))
        {
            // Calculate x and y which center the image
            int y = (maxHeight/2) - newHeight / 2;
            int x = (maxWidth / 2) - newWidth / 2;
    
            // Draw image on x and y with newWidth and newHeight
            graphics.DrawImage(image, x, y, newWidth, newHeight);
        }
    
        return newImage;
    }
    

提交回复
热议问题