High quality image resize (C#)

You can use this class to resize images proportionally (maintaining aspect ratio), or to resize an image to an exact size and crop off excess (useful for making nice thumbnails):

public static class ImageExt
{
    public static Image Resize(this Image img, int srcX, int srcY, int srcWidth, int srcHeight, int dstWidth, int dstHeight)
    {
        var bmp = new Bitmap(dstWidth, dstHeight);
        using (var graphics = Graphics.FromImage(bmp))
        {
            graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
            graphics.CompositingMode = CompositingMode.SourceCopy;
            graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
            using (var wrapMode = new ImageAttributes())
            {
                wrapMode.SetWrapMode(WrapMode.TileFlipXY);
                var destRect = new Rectangle(0, 0, dstWidth, dstHeight);
                graphics.DrawImage(img, destRect, srcX, srcY, srcWidth, srcHeight, GraphicsUnit.Pixel, wrapMode);
            }
        }
        return bmp;
    }

    public static Image ResizeProportional(this Image img, int width, int height, bool enlarge=false)
    {
        double ratio = Math.Max(img.Width / (double)width, img.Height / (double)height);
        if (ratio < 1 && !enlarge) return img;
        return img.Resize(0, 0, img.Width, img.Height, M2.Round(img.Width / ratio), M2.Round(img.Height / ratio));
    }

    public static Image ResizeCropExcess(this Image img, int dstWidth, int dstHeight)
    {
        double srcRatio = img.Width / (double)img.Height;
        double dstRatio = dstWidth / (double)dstHeight;
        int srcX, srcY, cropWidth, cropHeight;

        if (srcRatio < dstRatio) // trim top and bottom
        {
            cropHeight = dstHeight * img.Width / dstWidth;
            srcY = (img.Height - cropHeight) / 2;
            cropWidth = img.Width;
            srcX = 0;
        }
        else // trim left and right
        {
            cropWidth = dstWidth * img.Height / dstHeight;
            srcX = (img.Width - cropWidth) / 2;
            cropHeight = img.Height;
            srcY = 0;
        }

        return Resize(img, srcX, srcY, cropWidth, cropHeight, dstWidth, dstHeight);
    }
}
Posted in

2 thoughts on “High quality image resize (C#)

  1. Hi There,

    I have a bmp image that is 1500 x 1200 pixels I would like it to be 40% smaller, how would I do this with your code i.e. make the image 900 x 720 ?

    thank you

    Schuster

  2. Just need to do a little bit of math. Use

    ResizeProportional(img, img.Width*0.6, img.Height*0.6)

    I just noticed I used a function called

    M2.Round

    which I didn’t define. That’s simply

    (int)Math.Round

    .

Leave a Reply

Your email address will not be published. Required fields are marked *