C# Resized images have black borders

Ievgen Naida picture Ievgen Naida · Dec 7, 2009 · Viewed 12k times · Source

I have a problem with image scaling in .NET. I use the standard Graphics type to resize images like in this example:

public static Image Scale(Image sourceImage, int destWidth, int destHeight)
{
        Bitmap toReturn = new Bitmap(sourceImage, destWidth, destHeight);

        toReturn.SetResolution(sourceImage.HorizontalResolution, sourceImage.VerticalResolution);

        using (Graphics graphics = Graphics.FromImage(toReturn))
        {
            graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
            graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
            graphics.DrawImage(sourceImage, 0, 0, destWidth, destHeight);
        }
        return toReturn;
    }

But I have a big problem with resized images: they have gray and black borders and it's extremely important to make have images without them.

Why do they appear and what I can to do make them disappear?

Sample Output:

sample output

Answer

Mark Ransom picture Mark Ransom · Dec 7, 2009

Try:

graphic.CompositingMode = CompositingMode.SourceCopy;