Search code examples
.netgraphicsscalingsystem.drawing

Scale image to fixed-size canvas in .NET


I have a fixed-size canvas (e.g. presentation slide). Need to embed a picture into it without any quality distortion. If the image is smaller than the canvas, it must be centered. If it's larger, it has to be scaled down to fit.

Does any reliable algorithm exist or I have to create it from scratch?


Solution

  • The scaling you need is simply

    scale = desired size / actual size
    

    To avoid distortion you apply the same scale to both the height and width.

    To ensure you get the right size you find the longest dimension and scale using that so your code becomes:

    if (height > width)
    {
        scale = desiredHeight / actualHeight;
    }
    else
    {
        scale = desiredWidth / actualWidth;
    }
    

    Make sure you've converted the height and width to double values to avoid integer arithmetic.