1

So I'm trying to resize HUGE images, like 5500x3500 JPGs down to 1024x768 or less. The following function works, but it really runs the quality, makes the text all fuzzy.

static public Bitmap ScaleImage(Image image, int maxWidth, int maxHeight)
{
    var ratioX = (double)maxWidth / image.Width;
    var ratioY = (double)maxHeight / image.Height;
    var ratio = Math.Min(ratioX, ratioY);

    var newWidth = (int)(image.Width * ratio);
    var newHeight = (int)(image.Height * ratio);

    var newImage = new Bitmap(newWidth, newHeight);
    Graphics.FromImage(newImage).DrawImage(image, 0, 0, newWidth, newHeight);
    Bitmap bmp = new Bitmap(newImage);

    return bmp;
}

Any idea of a better way to do this?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291

2 Answers2

0

As suggested in comment, you should use Interpolation mode to control image quality during scaling. To know how to use it, refer to the following doc from Microsoft,

https://learn.microsoft.com/en-us/dotnet/framework/winforms/advanced/how-to-use-interpolation-mode-to-control-image-quality-during-scaling

Javed Ahmed
  • 406
  • 5
  • 21
0

You should set the quality-properties in Graphics-object to HighQuality:

static public Bitmap ScaleImage(Image image, int maxWidth, int maxHeight)
{
    var ratioX = (double)maxWidth / image.Width;
    var ratioY = (double)maxHeight / image.Height;
    var ratio = Math.Min(ratioX, ratioY);

    var newWidth = (int)(image.Width * ratio);
    var newHeight = (int)(image.Height * ratio);

    using (Bitmap newImage = new Bitmap(newWidth, newHeight))
    {
        using (Graphics g = Graphics.FromImage(newImage))
        {
            g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
            g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;

            Bitmap bmp = new Bitmap(newImage);
            return bmp;
        }
    } 
}

Also be sure to use using-block with objects that implements iDisposable: Image, Bitmap and Graphichs all do.

Esko
  • 4,109
  • 2
  • 22
  • 37