Resize a Bitmap in C# with Good Quality and Correct Proportions

Resizing an image with System.Drawing means creating a new Bitmap of the target size and drawing the original onto it with Graphics.DrawImage. The two-line version works, but the result is often blurry or has a faint gray border. The settings below fix that.

System.Drawing is Windows-only since .NET 6. WinForms projects (net8.0-windows) include it; a Windows console app needs the System.Drawing.Common package. For Linux, macOS or a web server in a container, see the ImageSharp section at the end.

Resize method

using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;

static Bitmap ResizeImage(Image source, int width, int height)
{
    var result = new Bitmap(width, height, PixelFormat.Format32bppArgb);
    result.SetResolution(source.HorizontalResolution, source.VerticalResolution);

    using Graphics g = Graphics.FromImage(result);
    g.CompositingMode = CompositingMode.SourceCopy;
    g.CompositingQuality = CompositingQuality.HighQuality;
    g.InterpolationMode = InterpolationMode.HighQualityBicubic;
    g.PixelOffsetMode = PixelOffsetMode.HighQuality;
    g.SmoothingMode = SmoothingMode.HighQuality;

    // Mirror the edge pixels so the filter does not blend in transparent black.
    using var attributes = new ImageAttributes();
    attributes.SetWrapMode(WrapMode.TileFlipXY);

    g.DrawImage(source,
        new Rectangle(0, 0, width, height),
        0, 0, source.Width, source.Height,
        GraphicsUnit.Pixel,
        attributes);

    return result;
}

Keep the aspect ratio

Usually you want the image to fit inside a box, say 800 × 800, without stretching it. Scale both sides by the same factor:

static Size FitWithin(Size original, int maxWidth, int maxHeight)
{
    double scale = Math.Min(
        (double)maxWidth / original.Width,
        (double)maxHeight / original.Height);

    return new Size(
        Math.Max(1, (int)Math.Round(original.Width * scale)),
        Math.Max(1, (int)Math.Round(original.Height * scale)));
}

Usage:

using var original = Image.FromFile(@"C:\images\photo.jpg");

Size size = FitWithin(original.Size, 800, 800);
using Bitmap resized = ResizeImage(original, size.Width, size.Height);

resized.Save(@"C:\images\photo-800.png", ImageFormat.Png);

A 4000 × 3000 photo becomes 800 × 600. If you only ever want to shrink, add scale = Math.Min(scale, 1) so small images are not blown up.

What each setting does

InterpolationMode.HighQualityBicubic decides how new pixels are computed from old ones. The default, bilinear, gives jagged results when you shrink an image a lot. High-quality bicubic is slower but is the right choice for photos. For pixel art that should stay crisp, use NearestNeighbor instead.

PixelOffsetMode.HighQuality shifts the sampling grid by half a pixel. Without it, the result is offset slightly up and to the left.

WrapMode.TileFlipXY fixes the gray or semi-transparent line along the edges. Bicubic filtering samples pixels outside the source image near its border; by default those count as transparent black. Mirroring the edge pixels gives the filter real data to work with.

CompositingMode.SourceCopy overwrites the destination pixels instead of blending with them, which is faster and keeps transparency exact.

SetResolution copies the DPI value. It does not change pixels, but some programs use it to decide the printed size.

The old version of this example called g.DrawImage(bmp, 0, 0, width, height) with default settings. It runs, and for a quick thumbnail that may be enough, but the output quality is visibly worse.

Saving JPEG with a quality setting

Save(path, ImageFormat.Jpeg) uses a fixed quality level. To choose it, pass the encoder and a quality parameter (0 to 100):

ImageCodecInfo jpegEncoder = ImageCodecInfo.GetImageEncoders()
    .First(codec => codec.FormatID == ImageFormat.Jpeg.Guid);

using var parameters = new EncoderParameters(1);
parameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 85L);

resized.Save(@"C:\images\photo-800.jpg", jpegEncoder, parameters);

The L suffix matters: the quality value must be a long. The fully qualified Encoder name avoids a clash with System.Text.Encoder.

Traps

  • Rotated phone photos. Cameras store orientation in EXIF metadata instead of rotating the pixels. System.Drawing ignores that tag, so a portrait photo can come out sideways after resizing. Read property item 0x0112 and call RotateFlip before resizing if this affects you.
  • Image.FromFile locks the file until the image is disposed. If you want to overwrite the original with the resized version, load it from a stream or dispose it before saving.
  • GetThumbnailImage looks like a shortcut but often returns the small, low-quality preview embedded in the JPEG. Use the method above.
  • Disposal. Every Bitmap holds unmanaged memory. In a loop over hundreds of files, missing using declarations will exhaust memory long before the garbage collector steps in.

Cross-platform: ImageSharp

ImageSharp (SixLabors.ImageSharp) runs everywhere .NET does, applies EXIF orientation on request and uses a high-quality resampler by default:

using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Processing;

using var image = Image.Load("photo.jpg");

image.Mutate(x => x
    .AutoOrient()
    .Resize(new ResizeOptions { Size = new Size(800, 800), Mode = ResizeMode.Max }));

image.Save("photo-800.jpg");

ResizeMode.Max fits the image inside the box while keeping its proportions, like FitWithin above. Check ImageSharp’s license terms for commercial use; SkiaSharp is an MIT-licensed alternative.

Related examples

2 thoughts on “Resize a Bitmap in C# with Good Quality and Correct Proportions”

Leave a Comment