Image Resize in C# - Algorith to determine resize dimensions (height and width)

后端 未结 5 1143
挽巷
挽巷 2020-12-28 23:32

I need to scale down an image that has a height or width greater than a predefined pixel value.

I wrote some code that takes a look at the original image, checks to

5条回答
  •  情话喂你
    2020-12-29 00:30

    The solution posted by Nathaniel actually fails if the image height is larger than the image width. The following example yields the correct result :

    private Size ResizeFit(Size originalSize, Size maxSize)
    {
        var widthRatio = (double)maxSize.Width / (double)originalSize.Width;
        var heightRatio = (double) maxSize.Height/(double) originalSize.Height;
        var minAspectRatio = Math.Min(widthRatio, heightRatio);
        if (minAspectRatio > 1)
            return originalSize;
        return new Size((int)(originalSize.Width*minAspectRatio), (int)(originalSize.Height*minAspectRatio));
    }
    

提交回复
热议问题