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

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

    You can avoid calculating the aspect ratio (and using doubles) using a few integer tricks..

    // You have the new height, you need the new width
    int orgHeight = 1200;
    int orgWidth = 1920;
    
    int newHeight = 400;
    int newWidth = (newHeight * orgWidth) / orgHeight; // 640
    

    or...

    // You have the new width, you need the new height.
    int orgWidth = 1920;
    int orgHeight = 1200;
    
    int newWidth = 800;
    int newHeight = (newWidth * orgHeight) / orgWidth; // 500
    

    The following example will resize an image to any desired rectangle (desWidth and desHeight) and center the image within that rectangle.

    static Image ResizeImage(Image image, int desWidth, int desHeight)
    {
        int x, y, w, h;
    
        if (image.Height > image.Width)
        {
            w = (image.Width * desHeight) / image.Height;
            h = desHeight;
            x = (desWidth - w) / 2;
            y = 0;
        }
        else
        {
            w = desWidth;
            h = (image.Height * desWidth) / image.Width;
            x = 0;
            y = (desHeight - h) / 2;
        }
    
        var bmp = new Bitmap(desWidth, desHeight);
    
        using (Graphics g = Graphics.FromImage(bmp))
        {
            g.CompositingQuality = CompositingQuality.HighQuality;
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            g.DrawImage(image, x, y, w, h);
        }
    
        return bmp;
    }
    

提交回复
热议问题