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

后端 未结 5 1168
挽巷
挽巷 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:33

    Here are two ways to make this calculation. Depending upon how you think about the problem, one may seem more intuitive than the other. They are mathematically equivalent to several decimal places.

    Both are safe for Math.Round, but only ConstrainVerbose produces results that are always less than maxWidth/maxHeight.

    SizeF ConstrainConcise(int imageWidth, int imageHeight, int maxWidth, int maxHeight){
        // Downscale by the smallest ratio (never upscale)
        var scale = Math.Min(1, Math.Min(maxWidth / (float)imageWidth, maxHeight / (float) imageHeight));
        return new SizeF(scale * imageWidth, scale * imageHeight);
    }
    
    SizeF ConstrainVerbose(int imageWidth, int imageHeight, int maxWidth, int maxHeight){
        // Coalculate the aspect ratios of the image and bounding box
        var maxAspect = (float) maxWidth / (float) maxHeight;
        var aspect =  (float) imageWidth / (float) imageHeight;
        // Bounding box aspect is narrower
        if (maxAspect <= aspect && imageWidth > maxWidth)
        {
            // Use the width bound and calculate the height
            return new SizeF(maxWidth, Math.Min(maxHeight, maxWidth / aspect));
        }
        else if (maxAspect > aspect && imageHeight > maxHeight)
        {
            // Use the height bound and calculate the width
            return new SizeF(Math.Min(maxWidth, maxHeight * aspect), maxHeight);
        }else{
            return new SizeF(imageWidth, imageHeight);
        }
    }
    

    Brute force unit-test here

提交回复
热议问题