Eric Bergman-Terrell's Blog

.NET Programming Tip: How to Attractively Scale Bitmaps
October 4, 2010

By default, the Graphics.DrawImage method scales Bitmaps efficiently but unattractively. To avoid ugly aliasing ("jaggies"), set the Graphics object's SmoothingMode, PixelOffsetMode, CompositingQuality, and InterpolationMode to high quality:

public static Bitmap Scale(Bitmap Bitmap, float ScaleFactorX, float ScaleFactorY)
{
    int scaleWidth  = (int)Math.Max(Bitmap.Width  * ScaleFactorX, 1.0f);
    int scaleHeight = (int)Math.Max(Bitmap.Height * ScaleFactorY, 1.0f);

    Bitmap scaledBitmap = new Bitmap(scaleWidth, scaleHeight);

    // Scale the bitmap in high quality mode.
    using (Graphics gr = Graphics.FromImage(scaledBitmap))
    {
        gr.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
        gr.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
        gr.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
        gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;

        gr.DrawImage(Bitmap, new Rectangle(0, 0, scaleWidth, scaleHeight), new Rectangle(0, 0, Bitmap.Width, Bitmap.Height), GraphicsUnit.Pixel);
    }

    // Copy original Bitmap's EXIF tags to new bitmap.
    foreach (PropertyItem propertyItem in Bitmap.PropertyItems)
    {
        scaledBitmap.SetPropertyItem(propertyItem);
    }

    return scaledBitmap;
}
Keywords: Graphics, Bitmap, Scaling, System.Drawing.2D, SmoothingMode, PixelOffsetMode, CompositingQuality, InterpolationMode, Graphics.DrawImage, aliasing, jaggies

Reader Comments

Comment on this Blog Post

Recent Posts

TitleDate
How to decompile Java code with JetBrains IntelliJ IDEA (2018.2.3, Windows 10)October 5, 2018
Java Programming Tip: SWT Photo Frame ProgramOctober 31, 2016
Vault 3 (Desktop) Version 1.63 ReleasedSeptember 9, 2016
"Compliance with Court Orders Act of 2016"April 9, 2016
Disable "Visual Voicemail" on Android / T-MobileJanuary 17, 2016
IPv6 HumorDecember 10, 2015
Java Programming Tip: Specify the JVM time zoneDecember 7, 2015